使用 RxJs v6 更新 2019 年 5 月
发现其他答案很有用,并希望为Arnaud提供的关于用法的答案提供一个例子。zip
下面是一个片段,显示了 rxjs 和 rxjs 之间的等价关系(另请注意,在 rxjs6 中,zip 现在如何使用“rxjs”而不是运算符导入)。Promise.all
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);
});
两者的输出是相同的。运行上述操作会得到:
{ 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!' ]