I am wondering if there's another way to auto subscribe/unsubscribe from an observable? I have seen async pipe mostly in html template, but what about when I want to do something in my component class, talking about when you're working in an angular project for example.
Asked
Active
Viewed 1,646 times
3
-
"auto unsubscribe" happens when the observable completes. So it depends on your observable. Do you have an endles stream, that never completes ? Then you must unsubscribe, or complete it via `pipe(takeWhile(() -> contition)) or pipe(takeUntil(observable)` or just unsubscribing. In case you ask you question because of the "httpClient" Observables, that result from a rest call take a look here : https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods – Luxusproblem Apr 12 '20 at 11:48
3 Answers
4
I would recommend one of the following unsubscribe methods:
- async pipe
- Using
takeUntil
operator:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
private readonly componentDestroyed$ = new Subject();
ngOnDestroy(): void { this.componentDestroyed$.next() }
ngOnInit(): void {
myObservable$.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
// your code here...
})
}
}
- Using subsink to help you manage subscriptions
- Using decorator-based approach such as ngx-auto-unsubscribe for angular < 9 or until-destroy for angular >= 9

Tal Ohana
- 1,128
- 8
- 15
1
You can probably create a base class to do so and extend it with your component class, then you don't have to repeat the ngDestory handling for every component that you created.
export class BaseComponent implements OnDestroy {
public _subscriptions: Subscription[] = [];
addSubscription(...sub): Subscription | Subscription[] {
this._subscriptions.concat(sub);
return sub;
}
ngOnDestroy(): void {
this._subscriptions.forEach(s =>
s.unsubscribe()
);
}
}
example usuage
class MyComp extends BaseComponent{
ngOnInit(){
this.addSubscription(interval(1000).subscribe())
}
}

Fan Cheung
- 10,745
- 3
- 17
- 39
0
You can make use of a behavior subject like this
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class ComponentA implements OnInit, OnDestroy {
private componentUnload$ = new Subject<boolean>();
constructor(
public dataService: DataService,
) {}
ngOnInit() {
this.dataService.items$ // here, you are calling an observable
.pipe(takeUntil(this.componentUnload$))
.subscribe(items => {
this.items = items;
});
}
ngOnDestroy(): void {
this.componentUnload$.next(true);
}

Syntiara
- 303
- 3
- 8