I'd like to convert the my nested Observables with the use of pipe,map,mergeMap, however there are conditions after which I want it to proceed
observableFunction is an Observable that loops through an array, once its finished you can move on to use the manipulated data
observableFunction(par1,par2)
.subscribe((resp) => {
i++;
//do stuff, manipulate resp
const lastIteration = someArray.length == i;
if (lastIteration) {
//do stuff
observableFunction(par1a, par2a)
.subscribe((resp) => {
observableHandleFunction(resp)
.subscribe((handledData) => {
h++;
const lastIterationSub = someNestedArray.length == h;
//do stuff, manipulate handledData
if (lastIterationSub) {
console.log("done");
});
});
}
});
How can I convert so that it does seem more easy to read by using the features of rxjs that are meant to be used in this scenario? Like applying conditions to mergeMap?
observableFunction(par1,par2)
.pipe(
mergeMap((res1) => {
//do stuff
CONDITION={
return observableFunction(par1a,par2a)
}
}),
mergeMap((res2) => return observableHandleFunction(res2))
)
.subscribe((res3) => {
h++;
//do stuff
const lastIterationSub = someNestedArray.length == h;
if (lastIterationSub) {
console.log("done");
}
});
With a solution something like this its not gonna work with the condition, leading to an error
First of all, nesting subscribe
blocks is always a bad idea.
If your observableFunction
emits single values (rather than a whole array at once) and when its done it emits a complete value, you can use toArray
operator. So:
observableFunction(par1,par2)
.pipe(toArray())
// Here you will have an array of items, now you can proceed with something like:
observableFunction(par1,par2)
.pipe(
toArray(),
mergeMap(array => {
// If neccesary you can do the same here etc
}))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.