Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
TheKarlo95 Avatar asked Mar 08 '17 20:03

TheKarlo95


2 Answers

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()
like image 83
Maksim Ostrovidov Avatar answered Oct 18 '22 02:10

Maksim Ostrovidov


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();
like image 22
onelaview Avatar answered Oct 18 '22 03:10

onelaview