Skip to content

Instantly share code, notes, and snippets.

@michaelbromley
Created August 23, 2017 08:27
Show Gist options
  • Save michaelbromley/abd6dfd8321a0e6c09c0257a3187062c to your computer and use it in GitHub Desktop.
Save michaelbromley/abd6dfd8321a0e6c09c0257a3187062c to your computer and use it in GitHub Desktop.
Managing Subscriptions in rxjs
/**
* 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