Created
August 23, 2017 08:27
-
-
Save michaelbromley/abd6dfd8321a0e6c09c0257a3187062c to your computer and use it in GitHub Desktop.
Managing Subscriptions in rxjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Two approaches to managing multiple Subscriptions in rxjs. | |
*/ | |
// Using a single Subscription | |
let subscription: Subscription; | |
// Using an array of Subscriptions | |
let subscriptions: Subscription[]; | |
function setup() { | |
const sub1 = Observable.interval(1).subscribe(() => { /* do something */}); | |
const sub2 = Observable.interval(1).subscribe(() => { /* do something */}); | |
const sub3 = Observable.interval(1).subscribe(() => { /* do something */}); | |
// Using the .add() method to group subscriptions | |
subscription = sub1 | |
.add(sub2) | |
.add(sub3); | |
// Using an array to group subscriptions | |
subscriptions = [sub1, sub2, sub3]; | |
} | |
function destroy() { | |
// Calling unsubscribe will also unsubscribe all added subscriptions | |
subscription.unsubscribe(); | |
// Or iterate over the array and unsubscribe from each individually | |
subscriptions.forEach(sub => sub.unsubscribe()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment