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)
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.)
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