Using a Subscription

There’s one more vocabulary word before this chapter is over: subscription. While piping through an operator returns an observable:

 let​ someNewObservable$ = anObservable$.pipe(
  map(x => x * 2)
 );

a call to .subscribe returns a Subscription:

 let​ aSubscription = someNewObservable$.subscribe(console.log);

Subscriptions are not a subclass of observables, so there’s no dollar sign at the end of the variable name. Rather, a subscription is used to keep track of a specific subscription to that observable. This means whenever the program no longer needs the values from that particular observable stream, it can use the subscription to unsubscribe from all future events:

 aSubscription.unsubscribe();

Some operators, like takeUntil above, handle subscriptions internally. Most of the time, your code manages subscriptions manually. We cover this in detail in Chapter 3, Managing Asynchronous Events. You can also “merge” subscriptions together or even add custom unsubscription logic. I recommend that you keep all logic related to subscribing and unsubscribing in the constructor function if possible, so that consumers of your observable don’t need to worry about cleanup.

 // Combine multiple subscriptions
 aSubscription.add(bSubscription);
 aSubscription.add(cSubscription);
 
 // Add a custom function that's called on unsubscribe
 aSubscription.add(() => {
  console.log(​'Custom unsubscribe function'​);
 });
 
 // Calls all three unsubscribes and the custom function
 aSubscription.unsubscribe();
..................Content has been hidden....................

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