最后更新:2021 年 6 月。
RxJS v7: combineLatestWith
来自 reactiveX documentation:
每当任何输入 Observable 发出一个值时,它都会使用所有输入的最新值计算一个公式,然后发出该公式的输出。
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
name$.pipe(
combineLatestWith((name, document) => {name, document})
)
.subscribe(pair => {
this.name = pair.name;
this.document = pair.document;
this.showForm();
})
(已弃用)RxJS v6 combineLatest()
来自 reactiveX documentation:
每当任何输入 Observable 发出一个值时,它都会使用所有输入的最新值计算一个公式,然后发出该公式的输出。
(更新:2021 年 2 月):
// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
name$.combineLatest(document$, (name, document) => {name, document})
.subscribe(pair => {
this.name = pair.name;
this.document = pair.document;
this.showForm();
})
(替代语法):combineLatest(observables)
// Deprecated (RxJS v6)
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
combineLatest(name$, document$, (name, document) => ({name, document}))
.subscribe(pair => {
this.name = pair.name;
this.document = pair.document;
this.showForm();
})
zip 与 combineLatest
(更新:2018 年 10 月)
我之前建议使用zip 方法。但是,对于某些用例,combineLatest 比 zip 有一些优势。因此,了解这些差异很重要。
CombineLatest 从 observables 发出最新的发射值。而zip 方法按sequence 顺序发出发射的项目。
例如,如果 observable #1 发出了它的 3rd 项,而 observable #2 发出了它的 5th 项。使用zip 方法的结果将是observables 的第3 个 发射值。
在这种情况下,使用 combineLatest 的结果将是 5th 和 3rd。感觉更自然。
Observable.zip(observables)
(原答案:2017 年 7 月) Observable.zip 方法在 reactiveX documentation 中解释:
组合多个 Observable 以创建一个 Observable,其值是按顺序根据其每个输入 Observable 的值计算得出的。
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
Observable
.zip(name$, document$, (name: string, document: string) => ({name, document}))
.subscribe(pair => {
this.name = pair.name;
this.document = pair.document;
this.showForm();
})
附注(适用于两种方法)
最后一个参数,我们提供了一个函数,(name: string, document: string) => ({name, document}) 是可选的。你可以跳过它,或者做更复杂的操作:
如果最新参数是一个函数,则该函数用于根据输入值计算创建值。否则,返回一个输入值数组。
所以如果你跳过最后一部分,你会得到一个数组:
// Observables to combine
const name$ = this._personService.getName(id);
const document$ = this._documentService.getDocument();
Observable
.zip(name$, document$)
.subscribe(pair => {
this.name = pair['0'];
this.document = pair['1'];
this.showForm();
})