godzsa
godzsa

Reputation: 2395

How to return Observable.empty() if observable.filter().first() returns nothing?

I have a function in RxJava which tries to find an Thing based on a condition, and if succeeds it transforms and returns it as an Observable. I want to return Observable.empty() if it is not able to find anything thus there is no first. I'm not sure about this, but I think if filter filters out every element in an Observable the result will be Observable.empty() anyway (without the firstElement()).

void Observable<Thing> transformFirst(Observable<Thing> things,Predicate<Thing> condition){
  return things
    .filter(condition)
    .firstElement()
    .map(firstThing ->{...do sg...})
}

EDIT:

My problem is that firstElement() returns a Maybe<Thing> and I do not know how to turn that into an Observable.empty() when the filter(condition) filters out everything (condition evaulates to false for every thing)

Upvotes: 2

Views: 4793

Answers (1)

arungiri_10
arungiri_10

Reputation: 988

You can add switchIfEmpty() as shown below,

return things
    .filter(condition)
    .switchIfEmpty(Observable.empty())
    .firstElement()
    .map(firstThing ->{...do sg...})

Upvotes: 9

Related Questions