Sourabh
Sourabh

Reputation: 8512

Return first emitted result from list of observables or return error if empty

I have a List<Observable<?>> and I want to get the first item emitted by any of these (running sequentially) or return error from last observable if all returned error or custom error if all were empty (which I can do with .switchIfEmpty(Observable.error(RuntimeException()))).

Currently, I have something like this:

Observable.fromIterable(listOfObservables)
        .take(1)
        .switchIfEmpty(Observable.error(RuntimeException()))

This code handles getting only first emitted value and returning an error if all observables were empty but don't handle error case. Any ideas how I can solve that part?

Upvotes: 0

Views: 481

Answers (1)

hgrey
hgrey

Reputation: 3093

This code should do what you want

Observable
  .fromIterable(listOfObservables)
  .concatMapDelayError(i -> i)
  .take(1)
  .switchIfEmpty(Observable.error(new RuntimeException()))

concatMapDelayError will process observables sequentially as requested and delay errors till the end, so if every observable is an error you will get CompositeException with all exceptions aggregated.

Upvotes: 1

Related Questions