Search code examples
rxjsobservablepublish-subscribeangular11

How Subscribe works


I am learning the rxjs and playing with observable and subscribe. I have the following method in component.ts file which returns true/false from API

this.http.get(apiUrl+"/actionName")
  .subscribe(result=> 
 {
 if(result){
     //step1
 //1.show success message 
  //2.call the other method 
  //3.and after returned from here
}else{// not true
 //1. show error message 
//2. returned from here
 }
});
});
 //step2
 // call another function
 }

Whenever I subscribe to an observable it immediately jumps to the next line i.e. step 2 and another method gets called first. Which I don't want to do.

I want to run step1 first until it gets finished completely only then it should go to step2. Thank you in advance.


Solution

  • You don't say so in your question, but I suspect your

    //2.call the other method
    

    line contains a nested subscription or a promise. If that's the case, of course your synchronous code will be run before your asynchronous code is run. JavaScript is a single-threaded environment, so you can never wait for other code to run.


    Instead, use RxJS various operators to manage the order of your code for you. How you want to do that depends on what you're doing, though sadly call the other method isn't descriptive enough.

    Assuming theOtherMethod and anotherFunction are actually strangely named observables, then you might do something like this:

    this.http.get(apiUrl+"/actionName").pipe(
    
      switchMap(result => {
        if(result){
          return theOtherMethod;
        }
        return of("There's no result")
      }),
    
      switchMap(otherMethodResult => anotherFunction)
    
    ).subscribe(anotherFunctionResult => {
      /* Ignore result?*/
    });