Emanuel Pinho
Emanuel Pinho

Reputation: 136

Observable - Stop sequence when a condition is met

I have an array of objects and I need to call a service that returns an observable, on each object, but I want to stop the sequence if some condition is met (e.g. service returns error).

const array = [
    {name: 'A', valid: true},
    {name: 'B', valid: true},
    {name: 'C', valid: false},
    {name: 'D', valid: true}
];

const fnc = (obj) => {
    console.log(obj.name);
    return of(obj.valid).pipe(delay(500));
};

In this case, what should be the Observable operator chain used to log only A and B?

Upvotes: 4

Views: 849

Answers (1)

martin
martin

Reputation: 96969

If you need to make a separate async to find out whether each item is valid you can simply use concatMap:

from(array).pipe(
    concatMap(obj => http.get(...).pipe(mapTo(obj))),
  })
  .subscribe(...);

You said that the service returns an error when an item is not valid so if the http.get call fails then concatMap emits an error.

However, if you want to just complete the chain without emitting an error (or if the service doesn't emit error when the item is not valid) you can use takeWhile():

from(array).pipe(
    concatMap(obj => http.get(...).pipe(
      map(valid => {
        obj.valid = valid;
        return obj;
      }),
    )),
    takeWhile(obj => obj.valid),
  })
  .subscribe(...);

Upvotes: 3

Related Questions