Tuesday, June 27, 2017

RxJava: Converting to Single type

In RxJava Single is a special type. It must emit exactly one value. Other types like Observable and Maybe can emit no values. If one is not careful these properties can lead to runtime errors in the code.

Converting a Maybe to Single

As shown by the tests in these examples this will rightly result in error.


Converting an Observable to Single

Oddly enough as converting an empty Observable to Single does not result in an error. Maybe that's a bug in RxJava implementation? A quick read of the code does seem to indicate that.

However, the javadoc of Observable#flatMapSingle says "Maps each element of the upstream Observable into SingleSources", and the method returns an Observable. So the behaviour is correct, the second snippet with a non-empty Observable shows that. Maybe the methods could have been named better?

Converting an Observable which emits too many values to a Single rightly results in an error.



Converting a Flowable to Single

Flowable exhibits same behaviour as Observable as shown in these snippets.



Converting a Completable to Single

Just for completeness (no pun intended), this works as expected.

1 comment: