Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); }); } 
like image 502
adam nowak Avatar asked Jun 10 '16 12:06

adam nowak


People also ask

What does pipe () do RxJS?

RxJS' pipe() is both a standalone function and a method on the Observable interface that can be used to combine multiple RxJS operators to compose asynchronous operations. The pipe() function takes one or more operators and returns an RxJS Observable.

What is of () RxJS?

RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.

How do I use concatMap?

To use concatMap in Angular first we need to import it our Component or Service. import { concatMap } from 'rxjs/operators'; In the following code, we have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D' . The ConcatMap receives its values from the srcObservable .


1 Answers

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.

like image 118
user3743222 Avatar answered Sep 20 '22 10:09

user3743222