Convert Callback to Kotlin Coroutines

December 28, 2018
suspend fun getMessage(liveData: LiveData<String>) = suspendCoroutine<String> { continuation ->
    liveData.observeForever(object : Observer<String> {
        override fun onChanged(message: String?) {
            message?.let {
                liveData.removeObserver(this)
                continuation.resume(message)
                continuation.resume(if (message == "ok") "" else "")
            }
        }
    })
}
launch {
    val echo = getMessage(liveData)
}

or

runBlocking {
    val echo = getMessage(liveData)
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.