Master RxJS: Part 2 – What is an observer

This is the second post in the Master RxJS series. The first post is a video tutorial that explains, why RxJS Watch it here:

In this post, we will discuss an observer in RxJS.

An observer is an object with three call-back functions to subscribe to the notifications from an Observable.

Too much technical jargon? Let us simplify it in this blog post. At the end of this post, you should able to understand each word in the above definition.

So, in RxJS, to work with an Observable, usually, you need to follow the steps as mentioned below,


Step 1 – Create an Observable

Step 2 – Subscribe to the Observable

Step 3 – Create an observer, and pass in the subscribe function to use the Observable

Step 4 – unsubscribe from the Observable


In simple words, an Observable push or emits data to the consumer, and an observer is an object used by the consumer to subscribe to those data.

An Observable can send three types of notifications. They are,

  1. Next data
  2. Error
  3. Complete

To understand the observer, let us start with step 1 and create an Observable. The below Observable emits four different data and complete notifications. It does not emit any error.


let observable = new Observable(subscriber => {
    subscriber.next(1);
    subscriber.next(2);
    subscriber.next(3);
    setTimeout(() => {
        subscriber.next(4);
        subscriber.complete();
    }, 1000);
});

In step 2, you can subscribe to the Observable by passing an observer

let foo = observable.subscribe(observer);

In Step 3, you have to create the observer, which is passed in step 2.


let observer = {
    next: (data: any) => console.log(data),
    error: (err: any) => console.log(err),
    complete: () => { console.log('complete') }
}

Here, you see that observer has three call back functions for three types of notifications from the Observable.

In Step 4, unsubscribe from the Observable


foo.unsubscribe();

You can also combine step 2 and step 3 and can subscribe to an Observable by directly passing the observer as shown below,


observable.subscribe(
    data => { console.log(data) },
    error => { console.log(error) },
    () => { console.log('complete ') }
)

Now you have seen four steps of working with an Observable, and what role an observer plays, let us focus on some essential characteristics of an observer.

The observer is partial

First and most important is that an observer is partial, which means you can opt to omit one of the call-backs, but the execution of the Observable will still happen, except notification cross ponds to omitted call-back would be ignored.  So, the below observer will work just fine.


observable.subscribe(
    data => {
        console.log(data);
    },
    null,
    () => {
        console.log('complete');
    }
)

As you see, in the above observer, there is no call-back function for the error notification, and null is passed there; hence the error is not handled at the consumer.

Each observer has its own subscribe function

Another important characteristic is an Observable is lazy means it does not start emitting value until it is not subscribed. So, to emit data from an Observable, it has to subscribe by a consumer. Also, for each observer, RxJS creates a new subscribe function in the Observable. So, the subscribe function is not shared among the observables.

Each observer has its own subscribe function. 

Consider the Observable created below,


function subscribe(subscriber: any) {
    let count = 0;
    setInterval(() => {
        count = count + 1;
        subscriber.next(count)
        if (count == 10) {
            subscriber.complete();
        }
    }, 1000);
}
 
const observable = new Observable(subscribe);

The Observable returns the count each 1000 millisecond, and when the count is equal to 10, it is completed.

Now let us create two consumers that will subscribe to the Observable.


observable.subscribe(
    data => {
        console.log('subscriber1 - ' + data);
    },
    null,
    () => {
        console.log('complete subscriber 1');
    }
)
 
const observer2 = {
    next: (data: any) => console.log('subscriber2-' + data),
    error: (err: any) => console.log(err),
    complete: () => { console.log('complete subscriber 2') }
}
 
setTimeout(() => {
    observable.subscribe(observer2);
}, 5000);

In the above example, observer2 starts to observe after 5000 MS, and you will find that both observers get independent counts from 1 to 10, that proves that each observer has its own subscriber function in the Observable.  Also, subscriber 2 starts observing after 500 MS, which means when the count for subscriber1 is already 6.

You should get an output as below,

So, RxJS creates an independent subscribe function for each observer for an Observable. However, if you are working with Subjects, the same subscribe will be shared across all the observers.

An observer is just an object with three call-back functions to subscribe to an Observable. I hope now you understand the observer, and in the next post, we will learn about the Observable.

If you like it share it 😊

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s