If I have a method that sometimes returns a string and sometimes returns a promise that results in a string how can I chain that in my observable?
Example
function doSomething() {
if (Math.random() < 0.5) {
return 'test';
}
return new Promise(resolve => resolve('test'));
}
const example = of(undefined).pipe(
mergeMap(() => doSomething())
);
const subscribe = example.subscribe(val => console.log(val));
I would like to always log "test".
mergeMap is a combination of Observable merge and map . There are times when your map or projection will generate multiple Observables. For example, now I have an array of characters, and for each character, I would like to make a backend call and get some information.
Use mergeMap if you simply want to flatten the data into one Observable, use switchMap if you need to flatten the data into one Observable but only need the latest value and use concatMap if you need to flatten the data into one Observable and the order is important to you.
So here's the simple difference — switchMap cancels previous HTTP requests that are still in progress, while mergeMap lets all of them finish. In my case, I needed all requests to go through, as this is a metrics service that's supposed to log all actions that the user performs on the web page, so I used mergeMap .
RxJS mergeMap() operator is a transformation operator that applies a project function on each source value of an Observable, which is later merged in the output Observable.
One way of solving the problem would be to make the function passed to mergeMap
an async
function and to await
the return value of doSomething
, like this:
const example = of(undefined).pipe(
mergeMap(async () => await doSomething())
);
You can do this because mergeMap
expects the function to return an ObservableInput
and a promise is a valid ObservableInput
.
Doing so takes advantage of that fact await
will accept either a promise or an ordinary value - to which the promise returned by the async
function will resolve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With