Promise.all RxJS Observables 的行为?

Promise.all behavior with RxJS Observables?

在 Angular 1.x 中,我有时需要发出多个 http 请求并对所有响应进行处理。我会把所有的承诺放在一个数组中并调用 Promise.all(promises).then(function (results) {...}).

Angular 2 个最佳实践似乎指向使用 RxJS 的 Observable 作为 http 请求中的承诺的替代品。如果我有两个或更多从 http 请求创建的不同 Observables,是否有等同于 Promise.all()?

模拟 Promise.all 的更直接的替代方法是使用 forkJoin 运算符(它并行启动所有 observables 并连接它们的最后一个元素):

有点超出范围,但如果它有帮助,关于链接承诺的主题,您可以使用简单的 flatMap :Cf。

forkJoin 也可以正常工作,但我更喜欢 combineLatest,因为您不必担心它会获取可观察对象的最后一个值。这样,只要它们中的任何一个也发出新值,您就可以得到更新(例如,您按时间间隔或其他方式获取)。

reactivex.io forkJoin actually points to Zip 上,它为我完成了工作:

let subscription = Observable.zip(obs1, obs2, ...).subscribe(...);

2019 年 5 月更新,使用 RxJs v6

发现其他答案很有用,并希望为 Arnaud 提供的关于 zip 用法的答案提供示例。

这里是一个显示 Promise.all 和 rxjs zip 之间等价的片段(另请注意,在 rxjs6 中,zip 现在是如何使用 "rxjs" 而不是作为运算符导入的)。

import { zip } from "rxjs";

const the_weather = new Promise(resolve => {
  setTimeout(() => {
    resolve({ temp: 29, conditions: "Sunny with Clouds" });
  }, 2000);
});

const the_tweets = new Promise(resolve => {
  setTimeout(() => {
    resolve(["I like cake", "BBQ is good too!"]);
  }, 500);
});

// Using RxJs
let source$ = zip(the_weather, the_tweets);
source$.subscribe(([weatherInfo, tweetInfo]) =>
  console.log(weatherInfo, tweetInfo)
);

// Using ES6 Promises
Promise.all([the_weather, the_tweets]).then(responses => {
  const [weatherInfo, tweetInfo] = responses;
  console.log(weatherInfo, tweetInfo);
});

两者的输出是一样的。 运行 以上给出:

{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]
{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]