Warm tip: This article is reproduced from stackoverflow.com, please click
angular observable rxjs subscription

How to perform one async action after another without embedded subscriptions

发布于 2020-04-13 10:39:19

I would like to perform async actions one after another using rxjs. I know that embedding subscribe in a subscribe is not a good practice and there are some other rxjs operators (flatMap\mergeMap, do etc. using pipe).

I need to get the component queryparams, set a global variable (globalVar), and only then, continue with the next async action (this..doSomething()). This is my code using embedded subscriptions: *doSomething return an observable

this.route.paramMap.subscribe(params => 
    { 
      globalVar = + params['userId']; 
      this.<someService>.doSomething().subscribe(result => 
      {
        this.func1();
      });
    }
Questioner
Guy E
Viewed
38
Християн Христов 2020-02-04 00:26

A perfect solution for the cases where you want to chain multiple observables is the switchMap operator.

this.route.paramMap
    .pipe(
      switchMap(params) => {
      globalVar = + params['userId']; 
      return this.<someService>.doSomething()
    })
    .subscribe(result=> {this.func1();})

The thing that switchMap will do is after getting the params from the this.route it will return a new observable, for which you can latter subscribe. The benefit of using switchMap in this case is that if there are changes inside the this.route.paramMap while the this.<someService>.doSomething() is processed, rxjs will kill the request that is being processed and start new one, by doing so the date in result inside the subscribe will always be relevant to the current value of paramMap.