I wanted to use RxJava but can't come up with alternative for method
public final Observable<T> first(Func1<? super T,java.lang.Boolean> predicate)
in RxJava2.
What I want to do is following:
return io.reactivex.Observable
.concat(source1, source2, source3, source4)
.first(obj -> obj != null);
Parameters source1 to source4 are io.reactivex.Observable
instances that I concatenate and I want resulting Observable to emit only the very first item that isn't null but this of course fails because io.reactivex.Observable
doesn't have method first(Func1 predicate)
like rx.Observable
.
What are my options if I have any in RxJava2 or is it better to stick with RxJava1?
Consider using Maybe
instead of Observable
of nullable type (it won't work with RxJava2). Then use Maybe.concat
to get only emitted items as Flowable
. And just get the first element with first
to return Single
(you have to specify a default item) or firstElement
to return Maybe
:
Maybe.concat(source1, source2, source3, source4)
.firstElement()
RxJava2 doesn't allow emitting null value as suggested by the others.
If, however, the predicate for determining what that first value to be returned is not to checking null, you may then consider using .filter
before .first
(need specifying some default value) or .firstOrError
(emit OnError instead if nothing matched)
return io.reactivex.Observable
.concat(source1, source2, source3, source4)
.filter(obj -> obj == someAnotherObj)
.firstOrError();
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