suspendCancellableCoroutine使用

在日常开发中经常会遇到需要挂起协程以等待某些[异步操作]完成的情况
Kotlin的协程为我们提供了丰富的挂起函数,其中一个非常重要且强大的函数就suspendCancellableCoroutine

什么是suspendCancellableCoroutine?

在Kotlin协程中,suspendCancellableCoroutine是一个挂起函数,它可以将异步回调转换为挂起函数调用。与suspendCoroutine不同的是,suspendCancellableCoroutine不仅可以挂起协程,还能支持取消协程的操作。这对于一些可能长时间运行或者需要响应取消请求的异步操作非常有用。

基本用法

让我们从一个简单的例子开始,来了解suspendCancellableCoroutine的基本用法:

import kotlinx.coroutines.*
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

fun main() = runBlocking {
    try {
        val result = fetchData()
        println("Result: $result")
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}

suspend fun fetchData(): String = suspendCancellableCoroutine { cont ->
    // 模拟异步操作 
    Thread {
        try {
            // 假装我们正在做一些网络请求 
            Thread.sleep(2000)
            cont.resume("Data fetched successfully")
        } catch (e: Exception) {
            cont.resumeWithException(e)
        }
    }.start()
} 

在这个示例中,我们创建了一个挂起函数fetchData,它使用suspendCancellableCoroutine来挂起协程,直到模拟的网络请求完成。

支持取消操作

suspendCancellableCoroutine的强大之处在于它可以响应取消操作。当协程被取消时,我们可以在回调中处理取消逻辑。下面是一个支持取消操作的示例:

suspend fun fetchDataCancellable(): String = suspendCancellableCoroutine { cont ->
    val thread = Thread {
        try {
            Thread.sleep(2000)
            if (cont.isActive) {
                cont.resume("Data fetched successfully")
            }
        } catch (e: Exception) {
            cont.resumeWithException(e)
        }
    }
    thread.start()
    cont.invokeOnCancellation {
        thread.interrupt()
        println("Fetch data operation was cancelled")
    }
} 

实际应用场景

网络请求

在实际开发中,我们经常需要进行网络请求,而网络请求通常是异步的。通过suspendCancellableCoroutine
,我们可以很方便地将网络请求转换为挂起函数,从而简化代码逻辑。例如:

suspend fun makeNetworkRequest(): String = suspendCancellableCoroutine { cont ->
    val call = OkHttpClient().newCall(Request.Builder().url("https://example.com").build())
    cont.invokeOnCancellation { call.cancel() }
    call.enqueue(object : Callback {
        override fun onResponse(call: Call, response: Response) {
            if (cont.isActive) {
                cont.resume(response.body?.string() ?: "")
            }
        }

        override fun onFailure(call: Call, e: IOException) {
            if (cont.isActive) {
                cont.resumeWithException(e)
            }
        }
    })
} 

在这个示例中,我们使用了OkHttp进行网络请求,并通过suspendCancellableCoroutine将其转换为挂起函数,同时处理了取消操作。

数据库操作

类似地,我们可以将异步的数据库操作转换为挂起函数。例如:

suspend fun queryDatabase(query: String): List<Data> = suspendCancellableCoroutine { cont ->
    val database = Database.getInstance()
    val cursor = database.rawQuery(query, null)
    cont.invokeOnCancellation { cursor.close() }
    // 模拟数据库查询 
    Thread {
        try {
            val data = mutableListOf<Data>()
            while (cursor.moveToNext()) {
                data.add(cursorToData(cursor))
            }
            if (cont.isActive) {
                cont.resume(data)
            }
        } catch (e: Exception) {
            cont.resumeWithException(e)
        } finally {
            cursor.close()
        }
    }.start()
} 

通过这种方式,我们可以更优雅地处理数据库查询操作,并确保在取消时关闭游标,防止资源泄漏。

深入理解CancellableContinuation

suspendCancellableCoroutine的核心是CancellableContinuation接口。它扩展了Continuation
接口,添加了取消相关的功能。下面是CancellableContinuation的一些重要方法:

  • resume(value: T): 恢复协程并返回结果。
  • resumeWithException(exception: Throwable): 恢复协程并抛出异常。
  • invokeOnCancellation(handler: (cause: Throwable?) -> Unit): 设置取消回调,当协程被取消时调用。
    通过这些方法,我们可以灵活地控制协程的恢复和取消逻辑。
小结

suspendCancellableCoroutine是Kotlin协程中一个非常强大的工具,它允许我们将异步回调转换为挂起函数,并支持取消操作。在实际开发中,我们可以利用它来简化网络请求、数据库操作等异步任务的处理。希望通过本文的介绍,大家能更好地理解和应用suspendCancellableCoroutine
,提升开发效率。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容