Kotlin实战经验:将接口回调转换成suspend挂起函数

Kotlin实战经验:将接口回调转换成suspend挂起函数_第1张图片

在 Kotlin 协程中, suspendCoroutinesuspendCancellableCoroutine 是用于将回调或基于 future 的异步操作转换成挂起函数。

suspendCoroutine

用途:将回调式异步操作转换为可挂起函数

行为:

  • 启动一个新的协程来处理基于回调的操作
  • 挂起当前协程,直到调用回调
  • 回调负责使用结果或异常恢复协程
  • 取消:需要在回调或启动的协程中手动取消逻辑,从而正确清理资源
suspend fun downloadFile(url: String): ByteArray {
   
    return suspendCoroutine {
    continuation ->
        val request = URL(url).openConnection() as HttpURLConnection
        request

你可能感兴趣的:(Kotlin,kotlin)