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}")}}
}