简体   繁体   English

forkJoin 上的 takeUntil 是否调用 forkJoined observables 上的函数?

[英]Does takeUntil on forkJoin calls the function on forkJoined observables?

When calling a forkJoin :调用forkJoin

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

The .pipe(takeUntil(onDestroy$)) is added to release observables when a component in Angular is destroyed.添加.pipe(takeUntil(onDestroy$))以在 Angular 中的组件被销毁时释放 observable。 Is this called on observableA and obserableB also?这是否也被 observableA 和 obserableB 调用? Or should it be called separately on all observables passed to forkJoin ?还是应该在传递给forkJoin所有 observable 上单独调用它?

It will automatically unsubscribe from the source observables.它将自动取消订阅源 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.在 2 秒内记录值然后停止。

The best way is using takeUntil as you do.最好的方法是像你一样使用takeUntil That's using it piped to forkJoin() .那是使用它通过管道传输到forkJoin() forkJoin() will automatically unsubscribe from all its source Observable (The source Observables are not completed. They are just unsubscribed). forkJoin()将自动取消订阅其所有源 Observable(源 Observable 未完成。它们只是取消订阅)。

The important thing is that if you use takeUntil on source Observables instead you won't get the same behavior.重要的是,如果您在源 Observables 上使用takeUntil ,您将不会得到相同的行为。

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. forkJoin()在其所有源 Observables 完成后发出,所以如果你的源 Observables 是例如FormControl.valueChangesActivatedRoute.queryParamMap那么完成它们将使forkJoin发射,这很可能不是你想要的。

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. forkJoin发出所有已完成 observable的最后一个值,因此根据定义,内部 observable 已经完成,因此您无需取消订阅它们。

Just having the .takeUntil on the forkJoin is enough只需在.takeUntil上使用forkJoin就足够了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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