Multicasting with the Subject Class

At its core, a Subject acts much like a regular observable, but each subscription is hooked into the same source, like the publish/share example. Subjects also are observers and have next, error, and done methods to send data to all subscribers at once:

 let​ mySubject = ​new​ Subject();
 
 mySubject.subscribe(val => console.log(​'Subscription 1:'​, val));
 mySubject.subscribe(val => console.log(​'Subscription 2:'​, val));
 
 mySubject.next(42);
 
 /*
  Console output:
  Subscription 1: 42
  Subscription 2: 42
 */

Because subjects are observers, they can be passed directly into a subscribe call, and all the events from the original observable will be sent through the subject to its subscribers.

 let​ mySubject = ​new​ Subject();
 
 mySubject.subscribe(val => console.log(val));
 
 let​ myObservable = interval(1000);
 
 // Multicast myObservable's data through mySubject
 myObservable.subscribe(mySubject);

Any Subject can subscribe to a regular observable and multicast the values flowing through it.

The general-purpose solution to our AJAX problem is an AsyncSubject, a specialized Subject that keeps track of the source observable and waits for it to complete. Then, and only then, does it pass on the resulting value to all subscribers. It also stores the value, and hands it to any new subscribers who jump in after the initial request is complete. Finally, we have a generalized solution for the user data AJAX problem:

 let​ user$ = ajax(​'/user'​);
 let​ asyncSub = ​new​ AsyncSubject();
 user$.subscribe(asyncSub);
 
 asyncSub.subscribe(val => console.log(​'sub 1:'​, val.response));
 
 // If the request completes before the subscription,
 // the subscription will still be called with the result
 setTimeout(() => {
  asyncSub.subscribe(val => console.log(​'sub 2:'​, val.response));
 }, 3000);

The first line creates an AJAX observable that points to the /user endpoint. The second line creates as a new instance of the AsyncSubject class. Since any Subject has next, error, and done methods, we can pass asyncSub directly into the subscribe call off of user$ on the third line. This subscribe immediately triggers the request to the backend. Before the call completes, a subscription to asyncSub is created. Nothing is logged until the request completes.

Once the server responds with the data, user$ passes it on to the single subscriber: asyncSub. At this point, two things happen. asyncSub emits to all current subscribers an event containing the response data, and it also records that data for itself. Later, when the setTimeout executes, asyncSub emits the same data to the second subscription.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.104.124