34

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:

  1. Is there a better way of doing this?
  2. Am I missing anything important that I should know - something like this actually doesn't behave as I'm expecting it to.
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Fred
  • 16,367
  • 6
  • 50
  • 65
  • There is `ignoreElement()` on Single. This basically converts a Single to Completable. Not solution for this case, but in one of my scenario, this avoided the need for Single.empty() for me. – rpattabi Sep 28 '18 at 13:41

2 Answers2

38

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.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
13

A workaround e.g. for tests would be

Observable.<Whatever>empty().toSingle()

keep in mind that this does not call the subscribers at all.

Florian Wolf
  • 141
  • 1
  • 5
  • I think this should be correct, with an explanation of what @akarnokd says. For me, it was useful to mock a Single and not worrying about the rest. – Rafael Ruiz Muñoz Jun 15 '18 at 12:59
  • Is this right? I'm new to kotlin but butting the generics in that position shows an error and toSingle doesn't seem to exist. Is there an updated version of this? Is Single.just(0) cheaper? – Nick Cardoso Aug 23 '21 at 08:15
  • use `Single.fromObservable()` – flamyoad Jul 20 '22 at 11:22