Coroutines instead of RxJava
Thursday, February 7, 2019RxJava was great. Really. But also complicated.
Look at this simple API call with RxJava:
api.getUser(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user ->
showUser(user)
}, { error ->
showError(error)
})
Now with coroutines:
val user = api.getUser(id)
showUser(user)
Wait what? Where is the threading stuff?
suspend functions
The magic is in suspend. You mark a function as suspend and it can be paused and resumed without blocking.
suspend fun loadUser(id: Int): User {
return withContext(Dispatchers.IO) {
api.getUser(id)
}
}
Call it from a coroutine scope and it just works. No callbacks, no operators to memorize.
When to still use RxJava
Honestly? Almost never for new code.
RxJava is still good for complex stream transformations. But for simple async operations coroutines are much easier to read and write.
Our team stopped using RxJava for new features in 2019. No regrets. The codebase became much simpler.
The learning curve is also way smaller. New team members can understand coroutines in a day. RxJava takes weeks.