Birth and Connection: Observable Creation and Subscription

Discover how data streams are born and consumed in Angular, the foundation of reactive programming.

💧

Welcome! Let's explore how Observables create powerful data streams in Angular.

/* Data streams incoming... */

The Blueprint: Creating an Observable

An Observable is created using the new Observable() constructor. It takes one argument: a function that runs when a consumer subscribes. This function defines what data to emit and when. It's the producer's logic.

The Connection: Subscribing to Listen

Nothing happens until you call the .subscribe() method on an Observable. This "turns on the tap" and connects the producer to a consumer. The function you pass to subscribe() will execute for every piece of data emitted.

The Stream: Pushing Data with `next()`

Inside the creation function, you get an observer object. You use its methods to send data. observer.next(value) sends a value to the consumer. This can be called multiple times, creating a stream of data over time.

The End: `complete()` and `error()`

A stream doesn't have to run forever. You can signal that it's finished by calling observer.complete(). No more values will be sent after this. Alternatively, if something goes wrong, observer.error(err) will stop the stream and notify the consumer of the error.

Practice Zone


Interactive Test 1: Match the Concepts

Drag the code snippet to the concept it represents.

Arrastra en el orden correspondiente.


Arrastra las opciones:

(observer) => { observer.next(1); }
(value) => { console.log(value); }

Completa el código:

Creation Logic______
Subscription Logic______
Unlock with Premium

Interactive Test 2: Complete the Code

Rellena los huecos en cada casilla.

import {  } from 'rxjs';

const myObservable = new Observable(observer => {
  observer.('Data 1');
  observer.();
});

myObservable.(data => {
  console.log(data);
});
Unlock with Premium

Practice Example: Code Editor

Create an Observable that emits three numbers (1, 2, 3) immediately and then completes. Subscribe to it and log the numbers to the console.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

import { Observable } from 'rxjs'; const numbers$ = new Observable(observer => { observer.next(1); observer.next(2); observer.next(3); observer.complete(); }); numbers$.subscribe(num => console.log(num));
Unlock with Premium

Knowledge Check

Which method do you call on an observer to send a value to a subscriber?


Unlock with Premium

Observables in the Angular Ecosystem

Creating your own Observables is powerful, but you'll most often use Observables provided by Angular's own APIs. Here’s where they shine.


1. HTTP Requests with `HttpClient`

When you make an API call with `HttpClient`, it doesn't return data directly. It returns an Observable that will emit the server's response once it arrives, and then automatically complete.

// Making a GET request
this.http.get('/api/users')
  .subscribe(users => {
    console.log('Users loaded:', users);
  });

2. Reactive Forms

Angular's Reactive Forms use Observables extensively. You can subscribe to `valueChanges` or `statusChanges` on a form control to react instantly as the user types or the form's validity changes.

// Listening to input changes in real-time
this.searchInput.valueChanges
  .pipe(debounceTime(300))
  .subscribe(value => {
    this.performSearch(value);
  });

3. Router Events

The Angular Router emits navigation events through an Observable. You can subscribe to `router.events` to execute logic during different stages of the routing lifecycle, like showing a loading spinner.

// Detecting navigation start and end
this.router.events.subscribe(event => {
  if (event instanceof NavigationStart) {
    this.loading = true;
  }
});

Practical Takeaway: Observables are the backbone of asynchronous and reactive programming in Angular. Mastering creation and subscription is the first step to harnessing their full potential throughout the framework.

Observable Glossary

Observable
Represents a stream of values that can be pushed over time. It's a blueprint for a data stream that does nothing until it is subscribed to.
Observer
The object passed to the Observable's creation function. It contains the methods (`next`, `error`, `complete`) used to push notifications to subscribers.
Subscription
The result of calling `.subscribe()` on an Observable. It represents the ongoing execution and provides a way to `unsubscribe()` and clean up resources.
next(value)
A method on the observer that sends a value to all subscribers. It can be called zero, one, or multiple times.
complete()
A method on the observer that signals the end of the stream. No more values will be sent after this notification.
error(err)
A method on the observer that signals an error has occurred. This immediately terminates the stream, and no `complete` notification will be sent.
RxJS
The "Reactive Extensions for JavaScript" library. It provides the implementation of Observables and a rich set of operators to manipulate them, and it is a core dependency of Angular.