A
A
Alexander Semenov2018-09-29 11:49:54
Angular
Alexander Semenov, 2018-09-29 11:49:54

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();
  }

The question is how to properly complete the entire chain of calls, tk. as far as I understand,
finalize(() => this.isLoading = false) is not called now, but takeUntil(this._onDestroy$) completes the subscription only to appState.event$ but not to service.getEvenContent()?
Or what to use instead of flatMap/mergeMap in such cases?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dasha Tsiklauri, 2018-09-29
@dasha_programmist

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

R
Ruslan Lopatin, 2018-09-29
@lorus

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 question

Ask a Question

731 491 924 answers to any question