How to do the chain sequence in rxjs

I would like to to something like:

this._myService.doSomething().subscribe(result => {
  doSomething()
});
.then( () => dosthelse() )
.then( () => dosanotherthing() )

So I would like to chain .then like in promise. How would I do that in Rxjs?

this._myService.getLoginScreen().subscribe( result => {
      window.location.href = MyService.LOGIN_URL;
      /// I would like to wait for the site to load and alert something from       the url, when I do it here it alerts the old one
    });
   .then (alert(anotherService.partOfTheUrl())


getLoginScreen() {
  return this.http.get(myService.LOGIN_URL)
.flatMap(result => this.changeBrowserUrl())
.subscribe( result => //i want to do sth when the page is loaded//);
}

changeBrowserUrl(): Observable<any> {
return Observable.create( observer => {
window.location.href = myService.LOGIN_URL;
observer.next();
});
}

Solution 1:

The equivalent of then for observables would be flatMap. You can see some examples of use here :

  • RxJS Promise Composition (passing data)
  • Why we need to use flatMap?
  • RxJS sequence equvalent to promise.then()?

For your example, you could do something like :

this._myService.doSomething()
  .flatMap(function(x){return functionReturningObservableOrPromise(x)})
  .flatMap(...ad infinitum)
  .subscribe(...final processing)

Pay attention to the types of what your functions return, as to chain observables with flatMap you will need to return a promise or an observable.

Solution 2:

If dosthelse or dosanotherthing returns a raw value, the operator to use is map. If it's an observable, the operator is flatMap (or equivalent).

If you want to do something imperatively. I mean outside the asynchronous processing chain, you could leverage the do operator.

Assuming that dosthelse returns an observable and dosanotherthing a raw object, your code would be:

this._myService.doSomething()
  .do(result => {
    doSomething();
  })
  .flatMap( () => dosthelse() )
  .map( () => dosanotherthing() );

Notice that if you return the return of the subcribe method, it will correspond to a subscription object and not an observable. A subscription object is mainly for being able to cancel the observable and can't take part of the asynchronous processing chain.

In fact, most of the time, you subscribe at the end of the chain.

So I would refactor your code this way:

this._myService.getLoginScreen().subscribe( result => {
  window.location.href = MyService.LOGIN_URL;
  /// I would like to wait for the site to load and alert something from       the url, when I do it here it alerts the old one
  alert(anotherService.partOfTheUrl()
});

getLoginScreen() {
  return this.http.get(myService.LOGIN_URL)
    .flatMap(result => this.changeBrowserUrl())
    .do( result => //i want to do sth when the page is loaded//);
}

changeBrowserUrl(): Observable<any> {
  return Observable.create( observer => {
    window.location.href = myService.LOGIN_URL;
    observer.next();
  });
}

Solution 3:

Updated rxjs solution

Rxjs has changed quite a bit since this was answered.

  • flatMap is now mergeMap
    • Or switchMap, they're mostly interchangeable but it's good to know the difference
  • .do() is now tap()
  • Chaining is now done inside of a .pipe(). All manipulation should be done inside this pipe
    • You can chain pipes if needed (Ex. one variable maps an array of Users. Another variable takes that first variable and maps it a second time)

Do something after the original call has been made

Scenario

  • Make an HTTP call (Ex. Authentication check)
  • When that call has finished, navigate to another page
this._myService.getAuthenticated()
  .pipe(
    tap(result => this._myService.navigateToHome())
  )
  .subscribe()

Chain multiple calls

Scenario

  • Make an HTTP call (Ex. Authentication check)
  • Make a 2nd call to pull more info
  • Navigate after both calls have finished
this._myService.getAuthenticated()
  .pipe(
    // The Authentication call returns an object with the User Id
    switchMap(user => this._myService.getUserInfo(user.id))
    // After the user has been loaded, navigate
    tap(user => this._myService.navigateToHome())
  )
  .subscribe()

Note on the above examples: I am assuming these calls are HTTP which unsubscribe after being called once. If you use a live observable (ex. a stream of Users), make sure you either unsubscribe or use takeUntil/first operators.