简体   繁体   中英

Does takeUntil on forkJoin calls the function on forkJoined observables?

When calling a forkJoin :

forkJoin(observableA, observableB)
  .pipe(takeUntil(onDestroy$))

The .pipe(takeUntil(onDestroy$)) is added to release observables when a component in Angular is destroyed. Is this called on observableA and obserableB also? Or should it be called separately on all observables passed to forkJoin ?

It will automatically unsubscribe from the source observables.

A simple test to confirm.

import { of, interval, forkJoin } from 'rxjs'; 
import { map, takeUntil, delay, tap } from 'rxjs/operators';

const source1 = interval(200).pipe(tap(i => console.log(i)));
const source2 = interval(300).pipe(tap(i => console.log('a' + i)));

const stop = of('stop').pipe(delay(2000));

forkJoin(source1, source2).pipe(takeUntil(stop)).subscribe();

logs values during 2 seconds then stops.

The best way is using takeUntil as you do. That's using it piped to forkJoin() . forkJoin() will automatically unsubscribe from all its source Observable (The source Observables are not completed. They are just unsubscribed).

The important thing is that if you use takeUntil on source Observables instead you won't get the same behavior.

forkJoin() emits after all its source Observables complete so if your source Observables are for example FormControl.valueChanges or ActivatedRoute.queryParamMap then completing them will make forkJoin to emit which is most likely not what you want.

According to the docs . The forkJoin emits the last value of all completed observables so by definition the inner observables are already completed, so you dont need to unsubscribe from them.

Just having the .takeUntil on the forkJoin is enough

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM