Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Created September 6, 2018 20:42
Show Gist options
  • Save ajcrites/d925389b574e1ce547c6199c5e29a79e to your computer and use it in GitHub Desktop.
Save ajcrites/d925389b574e1ce547c6199c5e29a79e to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { Subscription, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class SetupTearDownComponent extends React.Component {
// If component doesn't mount but is town down, create an empty
// subscription we can call `.unsubscribe` on
networkSubscription = new Subscription();
// Alternatively you can have one subject that you emit with and use
// takeUntil. This is useful if you have to manage many subscriptions.
// See also: https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
unmounted = new Subject();
componentDidMount() {
this.networkSubscription = network.changes.subscribe(handleChange);
network.changes.pipe(takeUntil(this.unmounted)).subscribe(handleChange);
}
componentWillUnmount() {
this.networkSubscription.unsubscribe();
this.unmounted.next();
this.unmounted.complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment