Convert a callback function to ordinary function

We have a function with a callback, e.g. fun withCallback(onResult: (Int) -> Unit) { ... } Some times it’s hard to call it from a linear code. Let’s assume we are OK to block and wait for the callback to happen. There is an easy to grab solution to it with Kotlin Coroutines.

The following trick will make it:

fun nonBlockingFunction() : Int = runBlocking {
  suspendCoroutine { cont -> withCallback { cont.resume(it) } }
}

So now we can call nonBlockingFunction directly from Kotlin or Java. Inside it will block and wait for callback to happen. Hope it will help.

This guest post has been written by Eugene Petrenko. Eugene, we truly appreciate your contribution!

Are you also interested in featuring your writings on Kotlintips.com? Then don’t hesitate to submit your own tips, and support a charity by doing so!

Leave a Reply

Your email address will not be published. Required fields are marked *