[英]rxjs, how to merge several requests, one serial request in parallel requests, and get one result
for example, I have 2 API service, returning type is Observable.例如,我有 2 个 API 服务,返回类型是 Observable。
function add(row) {
let r = Math.ceil(Math.random() * 2000);
let k = row + 1;
return timer(r).pipe(mapTo(k));
}
function mutiple(row) {
let r = Math.ceil(Math.random() * 2000);
let k = row * 10;
return timer(r).pipe(mapTo(k));
}
there is an array [1, 2, 3, 4, 5]
, I use the two function as follow:有一个数组
[1, 2, 3, 4, 5]
,我使用两个 function 如下:
from([1, 2, 3, 4, 5]).pipe(
mergeMap((row) => {
return add(row);
}),
mergeMap((row) => {
return mutiple(row);
}),
toArray()
).subscribe((_) => {
console.log("sub", _);
});
the result is结果是
sub [ 50, 20, 60, 40, 30 ]
the answer is that I want.答案是我想要的。
however, I don't know the source of the element of the array, I hope the result is但是,我不知道数组元素的来源,我希望结果是
[ [4, 50], [1, 20], [5, 60], [3, 40], [2, 30] ]
or或者
[
{ sourceData: 4, result: 50 },
{ sourceData: 1, result: 20 },
...
]
if I use contactMap to keep the sequence, the program will execute one by one, I don't care the sequence, I just wanna know how to connect the source and the result.如果我使用contactMap来保持序列,程序会一个一个地执行,我不在乎序列,我只想知道如何连接源和结果。
Thank you so much~非常感谢~
Try it in this way?用这种方式试试?
from([1, 2, 3, 4, 5]).pipe(
mergeMap((row) => {
const index$ = of(row);
return forkJoin([index$, add(row)]);
}),
mergeMap(([index, row]) => {
return forkJoin([of(index), mutiple(row)]);
}),
toArray()
).subscribe((_) => {
console.log("sub", _);
});
or或者
const handler = v => {
return of(v).pipe(
mergeMap((row) => {
return add(row);
}),
mergeMap((row) => {
return mutiple(row);
}),
)
}
from([1, 2, 3, 4, 5]).pipe(
mergeMap(row => forkJoin([of(row), handler(row)])),
toArray()
).subscribe((_) => {
console.log("sub", _);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.