Search code examples
javarx-javareactivexrx-java2

RxJava2: Alternative to rx.Observable method first(predicate)


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?


Solution

  • 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()