Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/50617221b3865c15abe83458257b92d4 to your computer and use it in GitHub Desktop.
Save killerchip/50617221b3865c15abe83458257b92d4 to your computer and use it in GitHub Desktop.
Angular tip: RxJS - Launch a series of requests one after the other

Launch a series of requests one after the other

In this example we launch a series of requests from information derived from an array. The requests are launched one after the other. This means a "next" request is launched only when the "previous" has been resolved.

The trick here is done by concatMap operator which does exactly what we want. So we create an Observable based on an array of initial values. Then concatMap will render them into a single stream the way we described above.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import { concatMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

...

const myEvents: number[] = [1, 2, 3, 4, 5];
const myobs = Observable.from(myEvents).pipe(
  concatMap (evt => {
    return this.http.get(`https://jsonplaceholder.typicode.com/postss/${evt}`);
  }),
)
.subscribe( /* handle events here */);

Bypass errors

The above approach, will stop the stream if one of the requests returns an error. What if we wanted to continue with the next requests even if one of them returned an error?

The materialize operator wraps all events (Events, Errors, Complete) to a new object called Notification. Thus errors and "complete" events are treated as normal events and do not stop the stream. Of course you have to handle the errors-complete events.

import { materialize } from 'rxjs/operators';

...
 return this.http.get(`https://jsonplaceholder.typicode.com/postss/${evt}`).pipe(
    materialize()
 )
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment