簡體   English   中英

RxJS-收集異步操作結果

[英]RxJS - Collect async operation results

我想對數組的每個元素執行異步操作,並將其結果收集在字典中。 我當前的方法是:

 let asyncOp = () => Rx.Observable.interval(300).take(1); let dict = {}; Rx.Observable.from(['a', 'b']) .mergeMap(el => asyncOp() .map(asyncOpRes => dict[el] = asyncOpRes) .do(state => console.log('dict state: ', dict)) ) .takeLast(2) .take(1) .map(() => dict) .subscribe(res => console.log('dict result: ', res)); 
 <script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script> 

基本上,這就像我想要的那樣工作,但是RxJs運算符的用法似乎很尷尬。 因此,我需要以下方面的幫助:

  1. 避免dict突變(使用scan()嘗試過,但是在這里不知道如何使用它。有一個mergeScan()方法,但在此相同)
  2. takeLast和take的用法-應該可以簡化嗎?

我想我缺少一個RxJS運算符,它可以幫助我簡化此操作。

要“對數組的每個元素執行異步操作並將其結果收集到字典中”,可以使用mergeMapreduce函數顯着簡化代碼:

import * as Rx from "rxjs/Rx";

const asyncOp = () => Rx.Observable.interval(300).take(1);

Rx.Observable.from(["a", "b"])

    // Perform the async operation on the values emitted from the
    // observable and map the emitted value and async result into
    // an object.

    .mergeMap((key) => asyncOp().map((result) => ({ key, result })))

    // Use reduce to build an object containing the emitted values
    // (the keys) and the async results.

    .reduce((acc, value) => { acc[value.key] = value.result; return acc; }, {})
    .subscribe((value) => { console.log(value); });

暫無
暫無

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

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