RXJS5 vs Promise.all

RXJS5 vs Promise.all

本文关键字:all Promise vs RXJS5      更新时间:2023-09-26

有Promise.all的等价物吗?

let prom1 = doA(); // some promise
let prom2 = doB(); // another promise
// wait for both promises to complete.
Promise.all([prom1, prom2], values => {
    // do something;
}); 

无法从文档中将其拼凑在一起,各种文章建议使用 ForkJoin,但无法让它工作......

let behaviour1 = new BehaviourSubject(0);
let behaviour2 = new BehaviourSubject(1);
let allObserver = new ForkJoinObservable(behaviour1, behaviour2);
behaviour1.subscribe( () => console.log('i work'));
behaviour2.subscribe( () => console.log('i work'));
allObserver.subscribe( () => console.log('i dont work'));

可能只是回到理智的承诺世界。

Rx.Observable有一个可用于复制Promise.all行为的toArray函数:它存储流的所有发出值,并等待底层流的onComplete事件触发。发出所有基础项后,生成的流将发出单个项:

// Instead of Promises, we can model our async actions as observables
const operation1$ = Rx.Observable.just(1);
const operation2$ = Rx.Observable.just(2);
// Merge all our async results into a single stream
const result$ = Rx.Observable.merge(operation1$, operation2$)
// Finally, call toArray to combine all results
result$
    .toArray()
    .subscribe(x => console.log(x));
// >> [1, 2]
import Rx, { Observable } from 'rxjs' 
import axios from 'axios'
const promiseA = axios.get('https://jsonplaceholder.typicode.com/users/1')
    , promiseB = axios.get('https://jsonplaceholder.typicode.com/users/2')
const promiseStream$ = Observable   
       .of(promiseA, promiseB)       // promises go here
       .flatMap(promise=>promise)    // resolve the promise under the hood         
       .map(response=>response.data)   
       .map(user=>user.name)   
       .subscribe(
           name=>console.log(`name is ${name}`)
           // name is Ervin Howell
           // name is Leanne Graham   
       )

flatMap(promise=>promise) flapMap 将帮助您解决引擎盖下的承诺

一种有点

俗气的方法是使用toPromise

Promise.all([behaviour1.toPromise(), behaviour2.toPromise()])

toPromise将返回一个承诺,该承诺在基础可观察量完成时解析。

但是,由于大多数可观察量在完成之前会发出 1 个以上的值,因此 zipcombineLatestwithLatestFrom 等操作可能更接近您要查找的内容:

.zip

行为

1 的每个值都会压缩为行为 2 的值。如果任一输入的值用完,它将停止,直到该输入再次具有值。

Observable.zip(behavior1, behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

另请参阅:文档、交互式大理石图

组合最新

与 zip 类似,但每次 behavior1 或 behavior2 发出值时都会发出一个值,并将重用另一个可观察对象的最新值进行配对。

Observable.combineLatest(behavior1, behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

另请参阅:文档、交互式大理石图

与最新发件人

与 combineLatest 一样,但只有一个可观察量确定何时发出值。

behavior1.withLatestFrom(behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

另请参阅:文档、交互式大理石图