Coroutine Context Switching Made Easy
Published in
1 min readJun 3, 2019
Kotlin Coroutines are great, there’s no denying that. But on Android, the CoroutineContext
matters so much; LiveData
and the UI need to be updated on Dispatchers.Main
, database and network operations need to be on Dispatchers.IO
, and everything else probably belongs on Dispatchers.Default
. So we end up with code like this:
withContext(Dispatchers.IO) { databaseQueryFunction() }.let {
withContext(Dispatchers.Main) {
liveData.value = it
}
}
Ideally, we’d have something like this:
onIO { databaseQueryFunction() }.onMain { liveData.value = it }
Lucky for you, I just added this to my (super small) ktx library. Give it a go and let me know what you think in the comments 😀.