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()
)
...