Answer the question
In order to leave comments, you need to log in
Proper Rxjs chain termination?
Good afternoon everyone.
There is this chain:
....
private _onDestroy$ = new Subject<void>();
....
this.appState.event$
.pipe(
flatMap((event: ICustomEvent) => {
if (event) {
this._event = event;
return this.service.getEvenContent(event.id, {
type: event.type,
date: event.date,
});
} else {
return throwError('Error');
}
}),
takeUntil(this._onDestroy$),
finalize(() => this.isLoading = false)
)
.subscribe(
result => {
this.content = result.text;
},
error => {
console.log(error);
}
);
....
ngOnDestroy(): void {
this._onDestroy$.next();
this._onDestroy$.complete();
}
Answer the question
In order to leave comments, you need to log in
To end a subscription, all you have to do is call unsubscribe() on the subscription, the object returned from the call to subscribe(). Also note that the flatMap body here will twitch every time the event is emitted, so it makes sense to call this.service.getEvenContent().first() so that there is no leakage, unless of course it is already called inside
finalize should be called as soon as there is data in this._onDestroy$ .
flatMap unsubscribes itself when necessary. That is, either when there is no data left in the getEvenContent chain, or when the result is unsubscribed.
Maybe it makes sense to use switchMap in order not to process data from getEvenContent for the previous event when a new one has already arrived?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question