
协程与结构化并发
|
207
13.2
使用
withContext
替换
async/await
问题
如何简化 async 启动协程,然后立即使用 await 等待其执行完毕的代码。
解决方案
将 async/await 的组合替换为 withContext。
讨论
CoroutineScope 类上也定义了一个名为 withContext 的扩展函数。它的签名如下
所示:
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T
文档中说 withContext“使用给定的协程上下文调用指定的挂起代码块,将其挂起直
到其执行完毕,最后返回结果。”在实践中,如示例 13-5 所示,将 async 调用后立即调
用 await 的代码替换为 withContext。
示例 13-5:使用 withContext 替换 async 与 await
suspend fun retrieve1(url: String) = coroutineScope {
async(Dispatchers.IO) {
println("Retrieving data on ${Thread.currentThread().name}")
delay(100L)
"asyncResults"
}.await()
}
suspend fun retrieve2(url: String) =
withContext(Dispatchers.IO) ...