Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical way to convert Completable to Single?

Tags:

kotlin

rx-java

I have an RxJava Completable that I want to execute, then chain to a Single<Long>. I can write it like this:

return Completable.complete().toSingleDefault(0L).flatMap { Single.just(1L) }

but this seems unnecessarily complicated. I would have thought Completable#toSingle() would do the job, but if I write:

Completable.complete().toSingle { Single.just(1L) }

I get errors. Is there a missing function in Completable or am I overlooking something?

like image 384
Clyde Avatar asked Jun 03 '18 01:06

Clyde


1 Answers

You probably want to use the andThen opeator, which will subscribe to the source you send to it after the Completable completes.

return Completable.complete()
    .andThen(Single.just(1L))

As @akarnokd said, this is a case of non-dependent continuations.

In case of your source needing to be resolved at runtime, this would be a deferred-dependent continuation, and you'd need to defer it:

return Completable.complete()
    .andThen(Single.defer(() -> Single.just(1L)))
like image 158
marianosimone Avatar answered Sep 18 '22 14:09

marianosimone