Convert Callback Into Kotlin Coroutines Suspend or Deferred

June 18, 2018
Use suspendCoroutine

Use suspendCoroutine.

launch(UI) {
    val result = suspendCoroutine<Boolean> { cont ->
        previewLayout.doOnLayout {
            cont.resume(true)
        }
    }
}

You can also convert it to a suspend function.

suspend fun test(): Boolean = 
    suspendCoroutine<Boolean> { cont ->
        previewLayout.doOnLayout {
            cont.resume(true)
        }
    }

Or you can use CompletableDeferred.

launch(UI) {
    val d = CompletableDeferred<Boolean>()
    previewLayout.doOnLayout {
        d.complete(true)
    }
    val result = d.await()
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.