Operators

RxJs provide a set of usefull operators, which are an elegant, declarative solution to complex asynchronous tasks.

concat

Subscribe to Observables in order but only when the previous completes, let me know, then move to the next one.

// Simulate HTTP requests 
const getPostOne$ = Rx.Observable.timer(3000).mapTo({id: 1});
const getPostTwo$ = Rx.Observable.timer(1000).mapTo({id: 2});

Rx.Observable.concat(getPostOne$, getPostTwo$).subscribe(res => console.log(res));

// Console Result:
// Object{id:1}
// Object{id:2}

Use this operator when the order is important, for example when you need to send HTTP requests that should be in order.

forkJoin

Using this operator observer will be notifed when all of observalbes will be complete, then emit result as array of all observable result.

const getPostOne$ = Rx.Observable.timer(1000).mapTo({id: 1});
const getPostTwo$ = Rx.Observable.timer(2000).mapTo({id: 2});

Rx.Observable.forkJoin(getPostOne$, getPostTwo$).subscribe(res => console.log(res))

mergeMap

Lets start from example

this.appParameters.subscribe(params => {
    const id = params['id'];
    if (id !== null && id!== undefined) {
      this.getUser(id).subscribe(user => this.user = user);
    }
  });

In this case we use result of first observable for method which return observable, there is a better way to acheive the same result - using mergeMap.

mergeMap(project: function: Observable, resultSelector: function: any, concurrent: number): Observable

For example above code we can transform to:

this.appParameters.pipe(mergeMap(params => {
  const id = params['id'];
    if (id !== null && id!== undefined) {
      return this.getUser(id);
    }
    return of(null);
  }
))).subscribe(user => this.user = user);

results matching ""

    No results matching ""