Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an observable to a maybe?

Tags:

rx-java2

There are new convenience methods added to rxjava2 added to accomplish a similar thing.

  • toSingle() converts an Observable that emits a single item into a Single that emits that item

  • toObservable() converts a Single into an Observable that emits the item emitted by the Single and then completes

How do can I convert an Observable to a Maybe?

(source: http://reactivex.io/documentation/single.html)

like image 836
Leroy Dunn Avatar asked Mar 17 '18 14:03

Leroy Dunn


1 Answers

You can't directly convert an Observable into a Maybe, because it wouldn't know what to emit in that context: is it the first element? the last? the product of some processing to the elements?

You can, however, decide on that and do what you want:

final Observable<Boolean> sourceBooleans = Observable.just(true, true, false);
final Maybe<Boolean> firstMaybe = sourceBooleans.firstElement();
final Maybe<Boolean> lastMaybe = sourceBooleans.lastElement();
final Maybe<Boolean> secondMaybe = sourceBooleans.elementAt(1);

final Observable<Integer> sourceNumbers = Observable.just(1, 2, 3, 4);
final Maybe<Integer> firstEven = sourceNumbers
    .filter(it -> it % 2 == 0)
    .firstElement()

You can see what methods return Maybe in the Observable implementation

Note that you can't go from Observable to Single directly either, without choosing what it should emit: there's no toSingle in the Observable class, but methods that return a Single instead (like first(), last(), etc.)

like image 160
marianosimone Avatar answered Sep 21 '22 09:09

marianosimone