3

let's say i don't use async pipe. and i want to subscribe something in component.ts file. as you know, i should unsubscribe myself if it's not http request.

here is what I tried.

way 1) implement ondestroy hook and unsubscribe there

way 2) when subscribing, use take(1) . take(1) will take care of unsubscribing itself.

my question is - why would anyone choose the way 1 and which one we should use when we want to unsubscribe (if we don't need async pipe)

Nika Kurashvili
  • 6,006
  • 8
  • 57
  • 123

1 Answers1

7

The answer has to do with Angular lifecycles.

Way 1. implement OnDestroy hook and unsubscribe there:

Your component does something like this, most likely in the OnInit method.

this.myObservable$.pipe(takeUntil(this.unsubscribe)).subscribe(myValue => {
  // do something
});

and you have a corresponding private variable and OnDestroy lifecycle hook to unsubscribe:

private unsubscribe: Subject<void> = new Subject();

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

You use this when you want the subscription to last for the lifetime of your component. As your observable receives new values, your subscription will continue to receive them.

Way 2. When subscribing, use take(1)

this.myObservable$.pipe(take(1)).subscribe(myValue => {
  // do something
});

This way will take the first emission and unsubscribe from the observable. Of course, if the value changes after that point, you won't be notified of changes.

Way 1 will help you maintain a dynamic state. Say you have a menu, and you want to select an option on that menu, you want this component to update when it changes, and whatever it is you need to do is complicated enough you can't use an async pipe. This subscription will last for the lifetime of the component.

Depending on what you are trying to do, you might not have to subscribe at all. Instead, you can use rxjs operators to do this work automatically. See https://brianflove.com/2017-11-01/ngrx-anti-patterns/ for example.

Edit:- Updated Link

trelston
  • 633
  • 1
  • 5
  • 13
David Rinck
  • 6,637
  • 4
  • 45
  • 60