我正在使用RxJS。我有两个Observable(API调用),它们为同一数组返回不同数量的信息。我想在Observables之间切换,并让订阅识别两种结果,即每次返回值时都触发。
这是一个使用Typescript的示例(此操作not无效:]
let foo = [];
const callOne$ = this.service.getSomeData$; // this should take 0.5 seconds
const callTwo$ = this.service.getAllTheData$; // this should take 6 seconds
callOne$.pipe(
switchMap(data => data.length > 0 ? callTwo$ : of(data)
).subscribe(data => {
console.log(data); // this fires once but I want it to fire twice
foo = data;
});
上面的示例检索callOne$
,然后检索callTwo$
,然后给我结果。相反,我希望两者的结果都井井有条。我将如何订阅Observables,以便接收第一个结果,然后在第二个调用中进行更新?
最简单的方法可能是
merge(callOne$, callTwo$)
.subscribe(data => {
console.log(data); // this fires twice but results are not guaranteed to be ordered
foo = data;
});
您可以保留订单,但发出单个事件并显示类似这样的内容
forkJoin(callOne$, callTwo$)
.subscribe(([data1, data2]) => { // this fires once with both results ordered
console.log(data1);
console.log(data2);
foo = data;
});
[如果您想让2个单独的通知维护该顺序,即首先是callOne $的结果,然后是callTwo $的结果,则可以尝试使用expand
运算符,如下所示:>
callOne$.pipe( expand(val => callTwo$), take(2) // to make sure you do not call callTwo$ infinitely ) .subscribe(data => { console.log(data); // this fires twice and the results are guaranteed to be ordered foo = data; });
[考虑到
foo
是一个数组的事实,您可能倾向于使用forkJoin
,即第二个选项。
您可以在this article中找到更详细的说明。
我发现最好的结果是使用concat()
,它依次响应Observable结果。