Rxjs subject switch map调用另一个observable

Rxjs subject switch map to call another observable

我正在尝试对主题中的每个发射值调用另一个可观察对象。

我现在的问题是 subject 的第一个发射值会触发 switchMap 并调用 confirmCsvUpload(...),但每个下一个发射值都会触发 switchMap 但是不是 confirmCsvUpload(...).

有人能弄清楚为什么它不调用该函数吗?

// Subject
private _confirmCsvUpload = new Subject<{ account: Account, previewData: PreviewData[], previewId: string }>();

// Subscription to the Subject 
this._confirmCsvUpload.pipe(
  switchMap(previewData => this._uploadCsvService.confirmCsvUpload(previewData.account, previewData.previewData, previewData.previewId))
).subscribe();

// Function which emits value to the subject (Not the function who gets called in the switchMap())
confirmCsvUpload(): void {
  this._confirmCsvUpload.next({ account: this.account, previewData: this._previewData, previewId: this.getPreviewIdFromRoute() });
}

我试着用以下方式重播你的风景:

  private _confirm$ = new Subject();
  private _destroy$ = new Subject();
  ngOnInit() {
    this._confirm$
      .pipe(
        takeUntil(this._destroy$),
        tap((v) => console.log('[SUB]', v)),
        switchMap((v: any) => this.secondCall())
      )
      .subscribe();
  }

  secondCall() {
    console.log('[SECOND CALL]');
    return of();
  }

  callSub() {
    console.log('[NEXT VALUE]');
    this._confirm$.next('value');
  }

  ngOnDestroy() {
    this._destroy$.next(null);
    this._destroy$.complete();
    console.log('[NG ON DESTROY]');
  }

包含 2 个调用的控制台日志:

[NEXT VALUE]
[SUB] value
[SECOND CALL]

-- 第二次:

[NEXT VALUE]
[SUB] value
[SECOND CALL]