Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 611
godzsa Avatar asked May 21 '26 17:05

godzsa


1 Answers

You can add switchIfEmpty() as shown below,

return things
    .filter(condition)
    .switchIfEmpty(Observable.empty())
    .firstElement()
    .map(firstThing ->{...do sg...})
like image 161
arungiri_10 Avatar answered May 24 '26 17:05

arungiri_10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!