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)
You can add switchIfEmpty() as shown below,
return things
.filter(condition)
.switchIfEmpty(Observable.empty())
.firstElement()
.map(firstThing ->{...do sg...})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With