Search code examples
kotlinrx-java2

Nested Completable stops observer chain


I want to execute a Completable in flatMap and "map" it to a specific value I need. The subscribe block is never executed. Why?

I'm aware of the existence of flatMapCompletable and andThen, but these don't solve my problem. This code is also a little simplified, in my real code I need to apply more operators to the nested Observable (derived from Completable), so I really need the conversion to Observable.

disposables += myPublishSubject.withLatestFrom(myObservable).flatMap { (_, result) ->
    myCompletable()
        .toObservable<Unit>()
        .map { result } // Return result of "parent" observable after Completable completes
}.subscribe { result ->
    Timber.i("result: $result") // Not executed!
}

Solution

  • Completables have no items thus when converted back to Observable, that Observable is also empty and thus never calls map. Use andThen(Observable.just(result)),

    disposables += myPublishSubject.withLatestFrom(myObservable).flatMap { (_, result) ->
        myCompletable()
            .andThen(Observable.just(result))
    }.subscribe { result ->
        Timber.i("result: $result") // Not executed!
    }
    

    or convert the Completable back to single with a default:

    disposables += myPublishSubject.withLatestFrom(myObservable)
    .flatMapSingle { (_, result) ->
        myCompletable()
            .toSingleDefault(result)
    }.subscribe { result ->
        Timber.i("result: $result") // Not executed!
    }