Disposing Subscriptions and Releasing Resources

In some scenarios we may want to unsubscribe from an Observable stream. Doing this is pretty straightforward as the .subscribe() call returns a data type that we can call .unsubscribe() on.

  1. export class MyApp {
  2. private data: Observable<Array<string>>;
  3. private value: string;
  4. private subscribed: boolean;
  5. private status: string;
  6. init() {
  7. this.data = new Observable(observer => {
  8. let timeoutId = setTimeout(() => {
  9. observer.next('You will never see this message');
  10. }, 2000);
  11. this.status = 'Started';
  12. return onUnsubscribe = () => {
  13. this.subscribed = false;
  14. this.status = 'Finished';
  15. clearTimeout(timeoutId);
  16. }
  17. });
  18. let subscription = this.data.subscribe(
  19. value => this.value = value,
  20. error => console.log(error),
  21. () => this.status = 'Finished';
  22. );
  23. this.subscribed = true;
  24. setTimeout(() => {
  25. subscription.unsubscribe();
  26. }, 1000);
  27. }
  28. }

View Example


Calling .unsubscribe() will unhook a member's callbacks listening in on the Observable stream. When creating an Observable you can also return a custom callback, onUnsubscribe, that will be invoked when a member listening to the stream has unsubscribed. This is useful for any kind of cleanup that must be implemented. If we did not clear the setTimeout then values would still be emitting, but there would be no one listening. To save resources we should stop values from being emitted. An important thing to note is that when you call .unsubscribe() you are destroying the subscription object that is listening, therefore the on-complete event attached to that subscription object will not get called.

In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time.

原文: https://angular-2-training-book.rangle.io/handout/observables/disposing_subscriptions_and_releasing_resources.html