csiki100
csiki100

Reputation: 43

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?

Upvotes: 4

Views: 2305

Answers (2)

ibenjelloun
ibenjelloun

Reputation: 7733

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

Upvotes: 4

Kamran Khatti
Kamran Khatti

Reputation: 4127

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

Upvotes: 2

Related Questions