Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2252
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

相关标签:
22条回答
  • 2020-11-21 05:25

    The official Edit #3 answer (and variations) works well, but the thing that gets me is the 'muddying' of the business logic around the observable subscription.

    Here's another approach using wrappers.

    Warining: experimental code

    File subscribeAndGuard.ts is used to create a new Observable extension to wrap .subscribe() and within it to wrap ngOnDestroy().
    Usage is the same as .subscribe(), except for an additional first parameter referencing the component.

    import { Observable } from 'rxjs/Observable';
    import { Subscription } from 'rxjs/Subscription';
    
    const subscribeAndGuard = function(component, fnData, fnError = null, fnComplete = null) {
    
      // Define the subscription
      const sub: Subscription = this.subscribe(fnData, fnError, fnComplete);
    
      // Wrap component's onDestroy
      if (!component.ngOnDestroy) {
        throw new Error('To use subscribeAndGuard, the component must implement ngOnDestroy');
      }
      const saved_OnDestroy = component.ngOnDestroy;
      component.ngOnDestroy = () => {
        console.log('subscribeAndGuard.onDestroy');
        sub.unsubscribe();
        // Note: need to put original back in place
        // otherwise 'this' is undefined in component.ngOnDestroy
        component.ngOnDestroy = saved_OnDestroy;
        component.ngOnDestroy();
    
      };
    
      return sub;
    };
    
    // Create an Observable extension
    Observable.prototype.subscribeAndGuard = subscribeAndGuard;
    
    // Ref: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
    declare module 'rxjs/Observable' {
      interface Observable<T> {
        subscribeAndGuard: typeof subscribeAndGuard;
      }
    }
    

    Here is a component with two subscriptions, one with the wrapper and one without. The only caveat is it must implement OnDestroy (with empty body if desired), otherwise Angular does not know to call the wrapped version.

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/Rx';
    import './subscribeAndGuard';
    
    @Component({
      selector: 'app-subscribing',
      template: '<h3>Subscribing component is active</h3>',
    })
    export class SubscribingComponent implements OnInit, OnDestroy {
    
      ngOnInit() {
    
        // This subscription will be terminated after onDestroy
        Observable.interval(1000)
          .subscribeAndGuard(this,
            (data) => { console.log('Guarded:', data); },
            (error) => { },
            (/*completed*/) => { }
          );
    
        // This subscription will continue after onDestroy
        Observable.interval(1000)
          .subscribe(
            (data) => { console.log('Unguarded:', data); },
            (error) => { },
            (/*completed*/) => { }
          );
      }
    
      ngOnDestroy() {
        console.log('SubscribingComponent.OnDestroy');
      }
    }
    

    A demo plunker is here

    An additional note: Re Edit 3 - The 'Official' Solution, this can be simplified by using takeWhile() instead of takeUntil() before subscriptions, and a simple boolean rather than another Observable in ngOnDestroy.

    @Component({...})
    export class SubscribingComponent implements OnInit, OnDestroy {
    
      iAmAlive = true;
      ngOnInit() {
    
        Observable.interval(1000)
          .takeWhile(() => { return this.iAmAlive; })
          .subscribe((data) => { console.log(data); });
      }
    
      ngOnDestroy() {
        this.iAmAlive = false;
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:25

    You usually need to unsubscribe when the components get destroyed, but Angular is going to handle it more and more as we go, for example in new minor version of Angular4, they have this section for routing unsubscribe:

    Do you need to unsubscribe?

    As described in the ActivatedRoute: the one-stop-shop for route information section of the Routing & Navigation page, the Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so you don't need to unsubscribe from the route paramMap Observable.

    Also the example below is a good example from Angular to create a component and destroy it after, look at how component implements OnDestroy, if you need onInit, you also can implements it in your component, like implements OnInit, OnDestroy

    import { Component, Input, OnDestroy } from '@angular/core';  
    import { MissionService } from './mission.service';
    import { Subscription }   from 'rxjs/Subscription';
    
    @Component({
      selector: 'my-astronaut',
      template: `
        <p>
          {{astronaut}}: <strong>{{mission}}</strong>
          <button
            (click)="confirm()"
            [disabled]="!announced || confirmed">
            Confirm
          </button>
        </p>
      `
    })
    
    export class AstronautComponent implements OnDestroy {
      @Input() astronaut: string;
      mission = '<no mission announced>';
      confirmed = false;
      announced = false;
      subscription: Subscription;
    
      constructor(private missionService: MissionService) {
        this.subscription = missionService.missionAnnounced$.subscribe(
          mission => {
            this.mission = mission;
            this.announced = true;
            this.confirmed = false;
        });
      }
    
      confirm() {
        this.confirmed = true;
        this.missionService.confirmMission(this.astronaut);
      }
    
      ngOnDestroy() {
        // prevent memory leak when component destroyed
        this.subscription.unsubscribe();
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:27

    Based on : Using Class inheritance to hook to Angular 2 component lifecycle

    Another generic approach:

    export abstract class UnsubscribeOnDestroy implements OnDestroy {
      protected d$: Subject<any>;
    
      constructor() {
        this.d$ = new Subject<void>();
    
        const f = this.ngOnDestroy;
        this.ngOnDestroy = () => {
          f();
          this.d$.next();
          this.d$.complete();
        };
      }
    
      public ngOnDestroy() {
        // no-op
      }
    
    }

    And use :

    @Component({
        selector: 'my-comp',
        template: ``
    })
    export class RsvpFormSaveComponent extends UnsubscribeOnDestroy implements OnInit {
    
        constructor() {
            super();
        }
    
        ngOnInit(): void {
          Observable.of('bla')
          .takeUntil(this.d$)
          .subscribe(val => console.log(val));
        }
    }

    0 讨论(0)
  • 2020-11-21 05:28

    For observables that complete directly after emitting the result like AsyncSubject or for example observables from http requests and such you don't need to unsubscribe. It doesn't hurt to to call unsubscribe() for those, but if the observable is closed the unsubscribe method will simply not do anything:

    if (this.closed) {
      return;
    }
    

    When you have long-lived observables that emit several values over time (like for example a BehaviorSubject or a ReplaySubject) you need to unsubscribe to prevent memory leaks.

    You can easily create an observable that completes directly after emitting a result from such long lived observables using a pipe operator. In some answers here the take(1) pipe is mentioned. But I prefer the first() pipe. The difference to take(1) is that it will:

    deliver an EmptyError to the Observer's error callback if the Observable completes before any next notification was sent.

    Another advantage of the first pipe is that you can pass a predicate that will help you to return the first value that satisfies certain criteria:

    const predicate = (result: any) => { 
      // check value and return true if it is the result that satisfies your needs
      return true;
    }
    observable.pipe(first(predicate)).subscribe(observer);
    

    First will complete directly after emitting the first value (or when passing a function argument the first value that satisfies your predicate) so there is no need to unsubscribe.

    Sometimes you are not sure about whether you have a long lived observable or not. I am not saying it is good practice but you could then always add the first pipe just to make sure you won't need to manually unsubscribe. Adding an additional first pipe on an observable that will emit only one value doesn't hurt.

    During development you can use the single pipe that will fail if source observable emits several events. This can help you to explore the type of observable and whether it is necessary to unsubscribe from it or not.

    observable.pipe(single()).subscribe(observer);
    

    The first and single seem very similar, both pipes can take an optional predicate but the differences are important and nicely summarized in this stackoverflow answer here:

    First

    Will emit as soon as first item appears. Will complete right after that.

    Single

    Will fail if source observable emits several events.


    Note I tried to be as accurate and complete as possible in my answer with references to the official documentation, but please comment if something important is missing...

    0 讨论(0)
  • 2020-11-21 05:29

    In case unsubscribe is needed the following operator for observable pipe method can be used

    import { Observable, Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    import { OnDestroy } from '@angular/core';
    
    export const takeUntilDestroyed = (componentInstance: OnDestroy) => <T>(observable: Observable<T>) => {
      const subjectPropertyName = '__takeUntilDestroySubject__';
      const originalOnDestroy = componentInstance.ngOnDestroy;
      const componentSubject = componentInstance[subjectPropertyName] as Subject<any> || new Subject();
    
      componentInstance.ngOnDestroy = (...args) => {
        originalOnDestroy.apply(componentInstance, args);
        componentSubject.next(true);
        componentSubject.complete();
      };
    
      return observable.pipe(takeUntil<T>(componentSubject));
    };
    

    it can be used like this:

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    
    @Component({ template: '<div></div>' })
    export class SomeComponent implements OnInit, OnDestroy {
    
      ngOnInit(): void {
        const observable = Observable.create(observer => {
          observer.next('Hello');
        });
    
        observable
          .pipe(takeUntilDestroyed(this))
          .subscribe(val => console.log(val));
      }
    
      ngOnDestroy(): void {
      }
    }
    

    The operator wraps ngOnDestroy method of component.

    Important: the operator should be the last one in observable pipe.

    0 讨论(0)
  • 2020-11-21 05:32

    I tried seangwright's solution (Edit 3)

    That is not working for Observable that created by timer or interval.

    However, i got it working by using another approach:

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import 'rxjs/add/operator/takeUntil';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    import 'rxjs/Rx';
    
    import { MyThingService } from '../my-thing.service';
    
    @Component({
       selector: 'my-thing',
       templateUrl: './my-thing.component.html'
    })
    export class MyThingComponent implements OnDestroy, OnInit {
       private subscriptions: Array<Subscription> = [];
    
      constructor(
         private myThingService: MyThingService,
       ) { }
    
      ngOnInit() {
        const newSubs = this.myThingService.getThings()
            .subscribe(things => console.log(things));
        this.subscriptions.push(newSubs);
      }
    
      ngOnDestroy() {
        for (const subs of this.subscriptions) {
          subs.unsubscribe();
       }
     }
    }
    
    0 讨论(0)
提交回复
热议问题