使用RxJS Observables的Promise.all行为?

Cor*_*urn 71 javascript observable rxjs angularjs

在Angular 1.x中,我有时需要提出多个http请求,并对所有响应做一些事情.我会把所有的promises抛出一个数组并调用Promise.all(promises).then(function (results) {...}).

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

use*_*222 68

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

有点超出范围,但如果它有所帮助,关于链接承诺的主题,你可以使用一个简单的flatMap:Cf.RxJS承诺组合(传递数据)


kak*_*ori 12

forkJoin工作得很好,但我更喜欢combineLatest,因为你不需要担心它会占用observables的最后一个值.这样,只要它们中的任何一个也发出新值,你就可以得到更新(例如你在一个间隔或某个东西上获取).

  • 这与Promise.all()没有达到相同的行为,但它类似于Promise.any() (2认同)

Arn*_*d P 10

reactivex.io forkJoin实际指向的拉链,是说这份工作对我来说:

let subscription = Observable.zip(obs1, obs2, ...).subscribe(...);
Run Code Online (Sandbox Code Playgroud)

  • forkJoin 等待所有可观察对象结束,而 zip 在所有输入发出其第一个值时发出一个数组。zip 可能会发出多次。如果你有 http 调用,那没有什么区别。 (3认同)

arc*_*don 8

使用RxJs v6更新2019年5月

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

这是显示Promise.all与rxjs 之间等效的代码段zip(另请注意,在rxjs6中,现在如何使用“ rxjs”而不是作为运算符来导入zip)。

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);
});
Run Code Online (Sandbox Code Playgroud)

两者的输出相同。运行上面的给出:

{ 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!' ]
Run Code Online (Sandbox Code Playgroud)