Subscription Class
Subscriptions
- Calling
Observable#subscribe()
returns aSubscription
- A
Subscription
lets you listen to next, error, and complete notifications from an observable - The
Subscription
object also enables you to unsubscribe from an observable
Creating a Subscription
We've already seen how to subscribe to an Observable:
source$.subscribe({
next: (value) => console.log(value),
error: (err) => console.error(err),
complete: () => console.log('Complete!'),
});
You can also subscribe without an object by using positional parameters:
source$.subscribe(
(value) => console.log(value),
(err) => console.error(err),
() => console.log('Complete!')
);
Joining Subscriptions
Calling subscribe returns a Subscription
object:
const subscription = source$.subscribe();
You can add additional subscriptions to the same subscription object:
const subscription = first$.subscribe();
subscription.add(second$.subscribe());
This can be useful for managing the subscription lifecycle of multiple observables
Subscription Class
You can create a Subscription
object on your own by newing up the Subscription
class:
const subscription = new Subscription();
subscription.add(source$.subscribe());