Angular - what is the preferred way to stop observing?

From my understanding of Angular and RxJs, there are two ways to terminate Observables. You can unsubscribe()either use them takeUntil()and complete(). Below are examples of each approach (in pseudo-code).

Unsubscribe () approach

private _id: number;
private _subscriptions: Subscription[] = [];

constructor(private _route: ActivatedRoute) {
    this._getId();
}

public ngOnDestroy(): void {
    this._subscriptions.forEach(
        subscription => subscription.unsubscribe()
    );
}

private _getId(): void {
    this._subscriptions.push(
        this._route.params.subscribe(params => this._id = +params['id'])
    );
}

Method takeUntil () and complete ()

private _id: number;
private _ngUnsubscribe: Subject<void> = new Subject<void>();

constructor(private _route: ActivatedRoute) {
    this._getId();
}

public ngOnDestroy(): void {
    this._ngUnsubscribe.next();
    this._ngUnsubscribe.complete();
}

private _getId(): void {
    this._route.params.takeUntil(this._ngUnsubscribe).subscribe(
        params => this._id = +params['id']
    );
}

In Angular, is there a preferred way to stop observing?

+6
source share
2 answers

Both approaches are correct, even if they are not equivalent.

In my opinion (and experience) using unsubscribe()usually makes more sense and is more obvious to other developers who do not have much experience with RxJS.

takeUntil() RxJS 5 (https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87) , . , partition() , takeUntil(...).partition(...).

:

  • . takeUntil(), Observable, , , . , unsubscribe(), ( , finally()).

    , unsubscribe(). takeUntil() complete, , ( , , complete, repeat(), ). , , , Observable . , unsubscribe().

    , .

  • Subscription :

    const subscription = new Subscription();
    
    const sub1 = Observable...subscribe(...);
    const sub2 = Observable...subscribe(...);
    const sub3 = Observable...subscribe(...);
    
    subscription.add(sub1).add(sub2).add(sub3);
    
    ...
    
    subscription.unsubscribe(); // unsubscribes all of them
    
+5

, , - ngOnDestroy, Observable . , . .

 accountSubscriptionObj : Subscription;

 ngOnDestroy() {
    if (this.accountSubscriptionObj) {
      this.accountSubscriptionObj.unsubscribe();
    }
  }

Async, @HostListener, . , , . , , , HTTP . .

0

All Articles