相关疑难解决方法(0)

如何在Kotlin延迟后调用一个函数?

作为标题,有没有办法在延迟后调用一个函数(例如1秒)Kotlin

android kotlin

110
推荐指数
10
解决办法
9万
查看次数

Kotlin 中 CoroutineScope 和 coroutineScope 的区别

任何人都可以明确功能之间的关系 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)

android suspend kotlin kotlin-coroutines coroutinescope

11
推荐指数
3
解决办法
9204
查看次数

CoroutineScope 和 withContext 之间的 Kotlin 区别

要更改函数中的线程,我使用 CoroutineScope 或 withContext。我不知道有什么区别,但是使用 CourineScope 我也可以使用处理程序。

例子:

private fun removeViews(){
    CoroutineScope(Main).launch(handler){
        gridRoot.removeAllViews()
    }
}

private suspend fun removeViews(){
    withContext(Main){
        gridRoot.removeAllViews()
    }
}
Run Code Online (Sandbox Code Playgroud)

我从一个在后台线程 (IO) 上工作的协程调用这个函数。哪个比另一个更合适?

android kotlin kotlin-coroutines

7
推荐指数
1
解决办法
832
查看次数

为什么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
查看次数