6

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?

TheKarlo95
  • 1,144
  • 9
  • 17

3 Answers3

5

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()
Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57
3

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();
onelaview
  • 1,121
  • 15
  • 17
1

first was renamed to firstElement. Also, Rx 2.0 doesn't support null values on the stream.

Rx.Java 2.0 Doc - 1.0 x 2.0