我一直是kotlin文档,如果我理解正确,两个kotlin函数的工作原理如下:
withContext(context):切换当前协同程序的上下文,当给定的块执行时,协同程序切换回上一个上下文.async(context):在给定的上下文中启动一个新的协同程序,如果我们调用.await()返回的Deferred任务,它将挂起调用协程并在生成的协同程序内执行的块返回时恢复.现在为以下两个版本code:
版本1:
launch(){
block1()
val returned = async(context){
block2()
}.await()
block3()
}
Run Code Online (Sandbox Code Playgroud)
版本2:
launch(){
block1()
val returned = withContext(context){
block2()
}
block3()
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
使用它并不总是更好,withContext而不是async-await功能相似,但不会创建另一个协同程序.大型数字协程,虽然轻量级仍然是要求苛刻的应用程序中的问题
是否有async-await更优先的案例withContext
更新:
Kotlin 1.2.50现在有一个可以转换的代码检查async(ctx) { }.await() to withContext(ctx) { }.
任何人都可以明确功能之间的关系 CoroutineScope()和coroutineScope()?
当我尝试检查源代码时,我发现它们都是CoroutineScope.kt. 此外,coroutineScope()是suspend函数而另一个是normal函数
以下是我可以找到的文档:
/**
* Creates a [CoroutineScope] that wraps the given coroutine [context].
*
* If the given [context] does not contain a [Job] element, then a default `Job()` is created.
* This way, cancellation or failure or any child coroutine in this scope cancels all the other children,
* just like inside [coroutineScope] block.
*/
@Suppress("FunctionName")
public fun CoroutineScope(context: CoroutineContext): CoroutineScope =
ContextScope(if (context[Job] != …Run Code Online (Sandbox Code Playgroud) withContext
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T (source)
Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.
Run Code Online (Sandbox Code Playgroud)
suspend fun <R> coroutineScope(
block: suspend CoroutineScope.() -> R
): R (source)
Creates a CoroutineScope and calls the specified suspend block with this scope. The provided scope inherits its coroutineContext from the outer scope, but overrides the context’s Job.
Run Code Online (Sandbox Code Playgroud)
withContext采用CoroutineContext,并且似乎都complete在其所有子级完成之后。
在什么情况下,withContext或者coroutineScope应该比其他的首选? …