我一直在阅读 kotlin docs,如果我理解正确的话,两个 Kotlin 函数的工作原理如下:
withContext(context): 切换当前协程的上下文,当给定块执行时,协程切换回以前的上下文。async(context): 在给定的上下文中启动一个新的协程,如果我们对返回的 Deferred任务调用 .await(),它将挂起调用协程,并在衍生协程中执行的块返回时恢复。下面是 code的两个版本:
第一版:
launch(){
block1()
val returned = async(context){
block2()
}.await()
block3()
}
第二版:
launch(){
block1()
val returned = withContext(context){
block2()
}
block3()
}
我的问题是:
Isn't it always better to use withContext rather than async-await as it is functionally similar, but doesn't create another coroutine. Large numbers of coroutines, although lightweight, could still be a problem in demanding applications.
Is there a case async-await is more preferable to withContext?
更新:
Kotlin 1.2.50 now has a code inspection where it can convert async(ctx) { }.await() to withContext(ctx) { }.