Sometimes I need a value from previous observable and run another function that depend on that value and so on. It make nested subcribe() calls and then code is very ugly and unmanageable. I have an example here:
getObservableData().subcribe(next=>
let dialogRef=this.dialog.open(EvalListComponent, {data: next})
dialogRef.afterClosed().subscribe(next=>{
let k=dialogRef.componentInstance.getAnotherObservableData()
.subcribe( next=> doSomthing(next))
}))
What kind of solution can have situation like that. I need some flatten structure. I know there is a pipe function and can be use it with rxjs operators. But how can be it accomplished?
To avoid nested subscribe calls you can always map back from a meta branch, such as a stream that has been forked from the main branch through some AJAX call or some other async operation, to a trunk branch by using mergeMap .
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 .
Nested subscriptions in use A very common use case is to request a data object from our API to then use some of its properties to request a few more related entities. Finally, we combine the received objects to fill our view. In Angular we could implement it like this: this.
mergeMap operator is basically a combination of two operators - merge and map. The map part lets you map a value from a source observable to an observable stream. Those streams are often referred to as inner streams.
I recommend this article: learn flattening strategies.
TLDR: use map operators like: mergeMap
, switchMap
, concatMap
, exhaustMap
.
All of them mostly work in the same manner —
They map some value to an observable (you are the one in charge of returning an observable value from them, they just map it)
They flatten the observable you return ( they just subscribe to it)
They decide about what to do before / after they flatten (“Flattening Strategy”)
Only thing you have to decide about is which strategy is useful for your example. By reading the article you can figure it out easily.
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