Callback => Coroutine,使用Coroutine代替Callback

interface CoroutineCallback {
    fun onSuccess(num: Int)
    fun onFailure(e: Exception)
}

object CoroutineDemoUtils {
    fun getDemoData(callback: CoroutineCallback) {
        val num = Random.nextInt(0, 9)
        if (num >= 5) callback.onSuccess(num)
        else callback.onFailure(Exception("number > 5"))
    }
}

suspend fun getCoroutineDemoData(): Int =
    suspendCancellableCoroutine {
        CoroutineDemoUtils.getDemoData(object : CoroutineCallback {
            override fun onSuccess(num: Int) {
                it.resume(num)
            }

            override fun onFailure(e: Exception) {
                it.resumeWithException(e)
            }
        })
    }

你可能感兴趣的:(Callback => Coroutine,使用Coroutine代替Callback)