协程 使用技巧 -- 回调转换

协程 使用技巧 – 回调转换

记录把回调转为协程的方法

回调转换为协程

  • 回调
interface Callback<T> {
    fun onSucceed(result: T)
    fun onFail(e: Exception)
}

fun getResultFromCallback() {
    // 用回调获取数据进行显示
    mockLongTimeProcess(object: Callback<String>{
        override fun onSucceed(result: String) {
            Log.i(TAG, "show result=$result")
        }

        override fun onFail(e: Exception) {
            Log.e(TAG, "e=${e.message}")
        }
    })
}

// 假装需要用力加载数据
fun mockLongTimeProcess(result: Callback<String>) {
    thread {
        Thread.sleep(3000)
        if (System.currentTimeMillis() % 2 == 0L) {
            result.onSucceed("Success")
        } else {
            result.onFail(Exception("Failure"))
        }
    }
}
  • 改成协程
// 看起来是顺序执行,实际会挂起等待结果再执行,但不阻塞线程
fun getResultFromCoroutine() {
    scope.launch {
        val result = try {
            getResult()
        } catch (e: Exception) {
            Log.e(TAG, "e=${e.message}")
            ""
        }
        Log.i(TAG, "result=$result")
    }
}

// 使用 suspendCancellableCoroutine 改造回调
suspend fun getResult() = suspendCancellableCoroutine {
    mockLongTimeProcess(object : Callback<String> {
        override fun onSucceed(result: String) {
            if (it.isCancelled) return
            it.resume(result)
        }

        override fun onFail(e: Exception) {
            it.resumeWithException(e)
        }
    })
}
  • suspendCoroutine 也能产生此效果,但无 cancel(),无法取消。而 suspendCancellableCoroutine 可以取消,并抛出 CancellationException 异常

回调转换为数据流

fun showResultFromFlow() {
    val flow = getResultFromFlow()
    launch {
        // 收到数据,刷一刷
        flow.collect {
            Log.i(TAG, "show $it")
        }
    }
}

// 冷流,人来疯
fun getResultFromFlow() = callbackFlow {
    // 辛苦得到了,立刻就射出去
    mockLongTimeProcess {
        try {
            trySend(it)
        } catch (e: Exception) {
            close(e)
        }
    }
    awaitClose {
        // 关闭时释放资源,释放了个寂寞
    }
}

// 假装需要用力加载数据流
fun mockLongTimeProcess(block: (String) -> Unit) {
    thread {
        for (i in 0 .. 6) {
            Thread.sleep(2000)
            block("Result: $i")
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值