Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does async pipe automatically unsubscribe from observable, if I change the observable?

I'm trying to make a language pipe with ngrx.

component.html:

<p>{{1 | language: languageId | async }}</p>

language pipe:

constructor(private store:Store){}

  transform(resourceId: number, languageId:number): Observable<string> {
    return this.store.select(selectResource, { resourceId, languageId });
  }

My question is, if I change the languageId in my component, then the pipe will select a new Observable from the store, but will the async pipe unsubscribe from the previous Observable, or do I have to do it manually?

like image 327
csiki100 Avatar asked Sep 19 '25 00:09

csiki100


2 Answers

Yes the async will handle the unsubscribe if the Observable instance has changed.

Here is a running example on stackblitz.

Pipe returning new observable every input change subscribed with async

like image 198
ibenjelloun Avatar answered Sep 21 '25 17:09

ibenjelloun


The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

When a new value is emitted, the async pipe marks the component to be checked for changes.

When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Find more details about async pipe here

like image 28
Kamran Khatti Avatar answered Sep 21 '25 17:09

Kamran Khatti