Kotlin回调函数转协程

本文介绍如何将传统的回调方法升级为协程,通过`suspendCancellableCoroutine`实现可取消的协程,提高代码安全性并简化异步操作。讲解了`suspendCancellableCoroutine`的使用方法和在实际场景中的应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        回调函数转协程通常使用两个协程相关的类:suspendCancellableCoroutine和suspendCoroutine,前者可以通过cancel()方法手动取消协程的执行,而suspendCoroutine没有该方法,调用cancel()后协程不再往下执行,抛出 CancellationException 异常,但是程序不会崩溃,这样会更加安全,通常推荐使用suspendCancellableCoroutine。

一、原始的回调方法

interface OnClickListener {
    fun onConfirm(index: Int)
    fun onCancel()
}

private fun method(listener: OnClickListener) {
    thread {
        Thread.sleep(3000)
        listener.onConfirm(3)
    }
}

private fun execute() {
    method(object : OnClickListener {
        override fun onConfirm(index: Int) {
            Log.d("TAG", "onConfirm: $index")
        }

        override fun onCancel() {
            Log.d("TAG", "onCancel: ")
        }
    })
}

二、使用协程

        suspendCancellableCoroutine接收一个匿名函数,参数为CancellableContinuation,他继承自Continuation,最常用的三个方法resume,resumeWith和resumeWithException。

private suspend fun execute(): Int {
    return suspendCancellableCoroutine {
        method(object : OnClickListener {
            override fun onConfirm(index: Int) {
                if (it.isCancelled) {
                    return
                }
                it.resumeWith(Result.success(index))
            }

            override fun onCancel() {
                it.resumeWith(Result.failure(Exception()))
            }
        })
    }
}

使用:


lifecycleScope.launch{
    val result = execute()
    Log.d("TAG", "result: $result")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值