I'm in the process of migrating from Rx 1 to Rx 2 and suddenly while reading through posts I found out that Single should be the type of observable to use for retrofit calls.
So I've decided to give it a shot and while migrating our retrofit calls to Rx 2 I also changed the return value to Single<whatever>
.
Now the issue is, some of our tests mock the network services something similar to:
when(userService.logout()).thenReturn(Observable.empty())
As you can see prior to migrating the calls we used to simply complete the stream by telling the userService
mock to return an empty observable.
While migrating to the Single
"version" of the calls we no longer can use Observable.empty()
because the call doesn't return an Observable
, but returns a Single
.
I've ended up doing something like:
when(userService.logout()).thenReturn( Single.fromObservable(Observable.<whatever>empty()))
My questions are:
Single. Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response. Sample Implementation: The below code always emits a Single user object.
Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.
Single.empty()
makes no sense because Single
has to have a single item or an error. You could just have kept Observable
or switched to Maybe
which does allow empty or Completable
which doesn't emit an item at all.
A workaround e.g. for tests would be
Observable.<Whatever>empty().toSingle()
keep in mind that this does not call the subscribers at all.
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