有人问到一些 SDK 封装的接口是异步回调的,无法修改内部的代码,但外面用的是协程,不好操作。实际上这里用 suspendCoroutine 即可。
代码:
private suspend fun test(): Boolean {
return suspendCoroutine<Boolean> { continuation ->
kotlin.runCatching {
//模拟异步代码块
}.onSuccess {
continuation.resume(true)
}.onFailure {
continuation.resume(false)
}.getOrThrow()
}
}其余:官方文档
以上。
本站广告由 Google AdSense 提供
0条评论