RxJS : Observables and Subjects

The purpose of this blog is to simplify the understanding process of Observables and Subjects, which seem confusing when we start learning these concepts.

First let’s understand Observables.

I. Observables:

As per the ReactiveX documentation,

An observer (sometimes called a “subscriber”, “watcher”, or “reactor”) subscribes to an Observable. An Observable emits items or sends notifications to its observers by calling the observers’ methods.

  • Observable emits a stream(of any data or events) over a period of time.
  • Observer subscribes and receives the stream.

Types of Observables:

  • Cold observable will send the data from the beginning of the subscription whenever a new observer subscribes.
    • For e.g. Playing a movie video, whenever you play, you can start with the beginning of the movie.
  • Hot observable will send the data from the point of the transmission where the new observer subscribes.
    • For e.g. Witnessing a live event. Whenever you join, you will witness the event from the moment you joined. You will not be able to see what happened before you joined in.

Creating an Observable as below:

 // Creating an observable to send some numbers with some delay
 this.data = new Observable(observer => {
 // 'next' is called to emit an item to the observer
 setTimeout(() => observer.next(42), 1000);
 setTimeout(() => observer.next(55), 2000);
 
 // 'complete' is called to signify that the data will be emitted no more
 setTimeout(() => observer.complete(), 3000);
 });

Subscribing to the observable (observer):

this.data.subscribe(
 // onNext
 value => this.values.push(value),
 
 // onError
 error => this.error = error,
 
 // onComplete
 () => this.completed = true;
 );

The observer looks like a try,catch and finally block, receiving the Observable.

// Observer
interface Observer<T> {
  onNext(value: T): void; // try
  onError(error: Error): void; // catch
  onCompleted(): void; // finally
}

Check the example in plunkr with an Observable and an observer.

II. Subject

Subject is a special type of Observable which can be both observer and observable together,

  • As an observer, it can subscribe to one or more Observables, and
  • As an Observable, it can pass through the items it observes by re-emitting them, and it can also emit new items.

Subjects are multicast,

  • They support multiple subscriptions and maintain a registry of many listeners.
  • Due to its dual capabilities, subjects act like a proxy between a group of subscribers and a source.
  • It can be used to implement a custom observable with capabilities like caching, buffering and time shifting and to broadcast data to multiple subscribers.

Create a Subject 

private subjectdata : Subject<number>;
this.subjectdata = new Subject();

Subject can emit data 

this.subjectdata.next(42);

Subject can subscribe to data

this.subjectdata.subscribe((value) => {
 this.values.push(value),
 console.log(value);
 );

Once subscribed, you will receive data emitted after subscribing  to it.

Check the plunkr code for Subject.

Types of Subjects

ReplaySubject: This stores all the values that it has published from the beginning. When you subscribe to it, you automatically receive an entire history of values that it has published, even though your subscription might have come in after certain values have been pushed out.

Check the same example using ReplaySubject.

BehaviorSubject: This only stores  the last value it published. It also requires a default value upon initialization. This value is sent to observers when no other value has been received by the subject yet. This means that all subscribers will receive a value instantly on subscribe, unless the Subject has already completed.

Check the example using BehaviorSubject.

AsyncSubject: This will only store the last value, and only publish it when the sequence is completed. You can use the AsyncSubject type for situations when the source observable is ‘hot’ and might complete before any observer can subscribe to it. In this case, AsyncSubject can still provide the last value and publish it to any future subscribers.

Check the example using AsyncSubject.

CONCLUSION

Hope this article has given you a basic understanding of Observables and Subjects with simple examples. We will explore more capabilities of these in future.

REFERENCES:

http://reactivex.io/rxjs/manual/overview.html#introduction

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 )

w

Connecting to %s