标签: withcontext

kotlin coroutines,coroutineScope和withContext有什么区别

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应该比其他的首选? …

kotlin-coroutines coroutinescope withcontext

8
推荐指数
1
解决办法
395
查看次数

为什么withContext等待子协程的完成

的文档withContext状态

用给定的协程上下文调用指定的暂停块,暂停直到完成,然后返回结果。

但是,实际行为是它也在所有子协程上等待,并且不一定返回块的结果,而是在子协程中传播任何异常。

suspend fun main() {
    try {
        val result = withContext(coroutineContext) {
            launch {
                delay(1000L)
                throw Exception("launched coroutine broke")
            }
            println("done launching")
            42
        }
        println ("result: $result")
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望可以打印出上述内容result: 42,然后再打印子协程中未捕获的异常。而是等待一秒钟,然后打印Error: launched coroutine broke

因此,实际行为与coroutineScope构建者的行为相匹配。虽然这可能是有用的行为,但我认为它与文档相矛盾。应该将文档更新为类似内容coroutineScope吗?

给定的块及其所有子协程完成后,此函数将立即返回。

此外,这是否意味着,我们可以使用coroutineScopewithContext(coroutineContext)互换,是少了几分样板唯一的区别?

kotlin kotlin-coroutines withcontext

4
推荐指数
1
解决办法
125
查看次数