3

I want to chain multiple request to the urls which I get from the array. Before next chain i want to wait for the previous one to finish. It's does not matter if the previous fails or not. I was trying to this with forkJoin but I know that if one of the request fails it will return error.

this.dataServers.forEach(dataServer => {
    observableBatch.push(this.getFoodsByQuery(dataServer.url, query));
});

return Observable.forkJoin(observableBatch).subscribe(data => {
    this.searchingServer.next(null);
    observer.complete();
});

I do not know how to do this with flatMap.

Stefan
  • 1,431
  • 2
  • 17
  • 33
  • Possible duplicate of [How to force observables to execute in sequence?](https://stackoverflow.com/questions/43336549/how-to-force-observables-to-execute-in-sequence) – martin Oct 12 '17 at 20:34

2 Answers2

8

In your case suitable operator is concat

Concatenates multiple Observables together by sequentially emitting their values, one Observable after the other.

Example:

// Batch of requests
let batch = [
  Observable.of(1),
  Observable.of(2).delay(1500),
  Observable.throw('Error'),
  Observable.of(3).delay(300),
  Observable.throw('Error again'),
  Observable.of(4).delay(600)
];

// Catch (ignore) error of every request
batch = batch.map(obs => {
  return obs.catch(err => Observable.of(err));
});

// Concat observables 
Observable.concat(...batch).subscribe({
  next: v => console.log(v),
  complete: () => console.log('Complete')
});

Output:

1
2
'Error'
3
'Error again'
4
'Complete'
taras-d
  • 1,789
  • 1
  • 12
  • 29
  • It looks great I have edited my question code and in this situation i have to subscribe to v and my problem is fact that complete is resolve before I subscribe to all next. – Stefan Oct 12 '17 at 20:49
  • I have another problem because i can not subscribe to v element but I need that `Observable.concat(...observableBatch).subscribe({ next: v => { v.subscribe(data => { this.searchingServer.next(this.dataServers[index]); index ++; observer.next(data); if(index == this.dataServers.length){ observer.complete(); this.searchingServer.next(null); } }) }, complete: () => console.log("complete") });` – Stefan Oct 13 '17 at 08:11
0

Have you tried using OnErrorResumeNext() with forkJoin?

return Observable.forkJoin(observableBatch)
.OnErrorResumeNext()
.subscribe(data => {
  this.searchingServer.next(null);
  observer.complete();
});
amburt05
  • 484
  • 3
  • 6