Sample of using coroutine continuation

Combine a standard callback with coroutines

Tiny project with a sample of combination of standard callback and coroutines.

Piece of code:

package com.gitlab.denissov.kcoroutines

import kotlinx.coroutines.runBlocking
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

fun main(args: Array<String>) {

    println("Start")
    runBlocking {
        val resultA = Converter("12345").await()
        println("ResultA: $resultA")

        try {
            val resultB = Converter("AAA").await()
            println("ResultB: $resultB")
        } catch (e: Exception) {
            println("ErrorB: $e")
        }
    }
    println("End")
}

interface ResultCallback<T> {

    fun onResult(data: T)

    fun onError(e: Exception)
}

class ConverterException(
    override val message: String? = null,
    override val cause: Throwable? = null
) : RuntimeException(message, cause)

class Converter(private val result: String) {

    fun enqueue(callback: ResultCallback<Int>) {
        try {
            callback.onResult(result.toInt())
        } catch (e: Exception) {
            callback.onError(ConverterException(cause = e))
        }
    }
}

suspend fun Converter.await(): Int = suspendCoroutine { continuation ->

    enqueue(object : ResultCallback<Int> {

        override fun onResult(data: Int) {
            continuation.resume(data)
        }

        override fun onError(e: Exception) {
            continuation.resumeWithException(e)
        }
    })
}

Result:

Start
ResultA: 12345
ErrorB: com.gitlab.denissov.kcoroutines.ConverterException
End

Code available at Repository