Kotlin协程序列:

1: 使用方式一 ,callback和coroutine相互转化。 

import kotlinx.coroutines.*
import java.lang.Exception
class MyCallback {
    fun doSomething(callback: (String?, Exception?) -> Unit) {
        // 模拟异步操作
        GlobalScope.launch {
            try {
                delay(1000) // 延迟 1 秒
                callback("Callback completed", null) // 回调成功
            } catch (e: Exception) {
                callback(null, e) // 回调失败
            }
        }
    }
}

suspend fun coroutineFunc() {
    println("Coroutine function called")
}

fun main() {
    val myCallback = MyCallback()
    val callbackToSuspend = suspendCoroutine<String> { continuation ->
        myCallback.doSomething { result, error ->
            if (error != null) {
                continuation.resumeWithException(error) // 将异常传递给协程
            } else {
                continuation.resume(result ?: "") // 将回调结果传递给协程
            }
        }
    }

    runBlocking {
        try {
            // 将回调函数转换成协程
            val job = launch { coroutineFunc() }
            // 执行回调函数
            println(callbackToSuspend)
            // 等待协程完成
            job.join()
        } catch (e: Exception) {
            // 处理异常
            println("Coroutine function failed: ${e.message}")
        }
    }
}

        

猜你喜欢

转载自blog.csdn.net/shaohuazuo/article/details/121878079