Convert Callback Into Kotlin Coroutines Suspend or Deferred

Jun 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()}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.