forkJoin为什么不发出值?

huangapple go评论69阅读模式
英文:

Why forkJoin does not emit value?

问题

这里有一个加载主题,触发了两个流。在这些流合并成一个之后:

this.sourceWithImage$ = this.load$.pipe(
  switchMap(() =>
    of(1).pipe(
      delay(3000),
      map(() => new Date().getMilliseconds())
    )
  )
);

this.sourceWithFields$ = this.load$.pipe(
  switchMap(() =>
    of(2).pipe(
      delay(2000),
      map(() => new Date().getMilliseconds())
    )
  )
);

this.sourceData$ = this.load$.pipe(
  switchMap(() => forkJoin([this.sourceWithImage$, this.sourceWithFields$]))
);

this.sourceData$.subscribe((e) => console.log(e));

为什么 forkJoin 没有发出值?我需要并行加载两个流。

英文:

There is a load$ subject that triggers two stream. After these streams forked into one:

this.sourceWithImage$ = this.load$.pipe(
  switchMap(() =>
    of(1).pipe(
      delay(3000),
      map(() => new Date().getMilliseconds())
    )
  )
);

this.sourceWithFields$ = this.load$.pipe(
  switchMap(() =>
    of(2).pipe(
      delay(2000),
      map(() => new Date().getMilliseconds())
    )
  )
);

this.sourceData$ = this.load$.pipe(
  switchMap(() => forkJoin([this.sourceWithImage$, this.sourceWithFields$]))
);

this.sourceData$.subscribe((e) => console.log(e));

Stackblitz link

Why forkJoin does not emit value?

I need to load two streams in parallel

答案1

得分: 1

forkJoin只有在所有输入都完成后才能发出值。

ForkJoin文档

等待Observables完成,然后组合它们最后发出的值;如果传递一个空数组,立即完成

因此,您可能想要使用 take(1) 或更改您的逻辑,像这样
Stackblitz示例

const load$ = new Subject();

const sourceWithImage$ = of(1).pipe(
  delay(3000),
  map(() => new Date().getMilliseconds())
);

const sourceWithFields$ = of(2).pipe(
  delay(2000),
  map(() => new Date().getMilliseconds())
);

const sourceData$ = load$.pipe(
  switchMap(() => forkJoin([sourceWithImage$, sourceWithFields$]))
);

sourceData$.subscribe({
  next: (v) => console.log(v),
  error: (e) => console.log(e),
});
load$.next(1);
英文:

forkJoin can only emit a value when all inputs have finished.

ForkJoin docs
> Wait for Observables to complete and then combine last values they emitted; complete immediately if an empty array is passed

So you may want to use take(1) or change your logic, like this
Stackblitz example

const load$ = new Subject();

const sourceWithImage$ = of(1).pipe(
  delay(3000),
  map(() => new Date().getMilliseconds())
);

const sourceWithFields$ = of(2).pipe(
  delay(2000),
  map(() => new Date().getMilliseconds())
);

const sourceData$ = load$.pipe(
  switchMap(() => forkJoin([sourceWithImage$, sourceWithFields$]))
);

sourceData$.subscribe({
  next: (v) => console.log(v),
  error: (e) => console.log(e),
});
load$.next(1);

huangapple
  • 本文由 发表于 2023年5月7日 16:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定