簡體   English   中英

如何有效地鏈接 RxJS Observables

[英]How to I effectively chain RxJS Observables

我知道這個問題已經在這里的各種 forms 中被問過幾次,但我正在努力讓它完全按照我的意願去做。

為了提供一些上下文,我在 NodeJS 中有一個文件上傳服務,它將圖像存儲在一個臨時文件夾中。 然后我有一些功能可以將圖像大小調整為常規 web 大小和縮略圖,然后保存到上傳文件夾,然后另一個 function 以刪除臨時文件。 所有這三個函數都返回 Observables。

我想要的是按順序運行這些可觀察對象,例如

observableA().subscribe((result) => //do something here ) // Resize the photo
observableB().subscribe((result) => //do something here ) // Create a thumbnail
observableC().subscribe((result) => //do something here ) // Delete the temporary file

我想確保 A 和 B 在執行 C 之前完成(刪除臨時文件夾)。 我不想嵌套 Observables。 A 和 B 都返回一些我想要的數據。

哪個是實現這一目標的最佳 rxJS 運算符?

您可以使用forkJoin組合前 2 個可觀察對象(它們將並行運行)。 然后使用switchMap切換到第三個 observable。

import { of, timer, forkJoin } from "rxjs";
import { switchMap, delay, map } from "rxjs/operators";

const observableA = of("resized photo").pipe(delay(300));
const observableB = of("thumbnail").pipe(delay(250));
const observableC = of("temp deleted").pipe(delay(100));

const result = forkJoin(observableA, observableB).pipe(
  switchMap(([resultA, resultB]) => {
    console.log(resultA, resultB);
    console.log('now to observableC');
    return observableC.pipe(map(resultC => [resultA, resultB, resultC]));
  })
);
result.subscribe(x => console.log(x));

stakblitz上查看(不要忘記打開控制台查看console.log輸出)。

RxJS 文檔還有一個方便的頁面,可幫助您為工作選擇正確的操作員: operator-decision-tree

您應該使用flatMap ,從某種意義上說then對於 observables,請記住 flatMap 實際上執行的是 function。

this._myService.do1()
  .flatMap(function(x){return functionReturningObservableOrPromise(x)})
  .flatMap(... return observable here tooo)
  .subscribe(get your data)

要保留順序,您應該使用concatMap運算符,並使用tap運算符來實現如下所示的副作用:

observableA()
  .pipe(
    concatMap(() => observable().pipe(tap(() => /* add some sides effects for this obs. */ )),
    tap(() => /* or add some sides effects here or somewhere else */ )),
    concatMap(() => observableC())
  )
  .subscribe();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM