Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding nested subcribe() calls in RxJs 6

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?

like image 392
Lakindu Akash Avatar asked Oct 09 '18 19:10

Lakindu Akash


People also ask

How do I stop nested observables?

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 .

What is the difference between mergeMap and SwitchMap?

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 .

What is nested subscription?

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.

What is mergeMap in angular?

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.


1 Answers

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 —

  1. They map some value to an observable (you are the one in charge of returning an observable value from them, they just map it)

  2. They flatten the observable you return ( they just subscribe to it)

  3. 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.

like image 171
gr4viton Avatar answered Oct 12 '22 21:10

gr4viton