https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Scott Kruse

07/27/2021, 9:36 PM
Looking at some code where RxJava is called from a suspend function. TLDR on why this is a bad idea?
Copy code
viewModelScope.launch {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                doStuff()
            }
        }

        suspend fun doStuff() {
            doStuffWithRx()
        }

        fun doStuffWithRx() {
            Single.fromCallable {
                // hit network 
            }
                    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSuccess { result ->
                    }
                    .subscribe()
        }
c

Casey Brooks

07/27/2021, 9:48 PM
the
Single
is not bound to the coroutine in any way. It’s just running in the background, completely unmanaged. There’s a coroutines artifact specifically for connecting RxJava to Coroutines (and vice-versa) which you should be using here,
Single.await()
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-rx2/index.html
👍 3
n

Nick Allen

07/27/2021, 9:48 PM
Specifically, if the coroutine is cancelled, the Single will not be cancelled. If the Single fails,
doStuff
will not throw an exception.
👍 1