gpt4 book ai didi

android - 对Kotlin协程感到困惑

转载 作者:行者123 更新时间:2023-12-02 13:29:15 26 4
gpt4 key购买 nike

这没有编译错误:

suspend fun test() {
runBlocking {

}
}

这有一个编译错误:
suspend fun test() {
launch {

}
}

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public fun CoroutineScope.launch(context: CoroutineContext = ..., start: CoroutineStart = ..., block: suspend CoroutineScope.() -> Unit): Job defined in kotlinx.coroutines



我不太明白是什么问题...

最佳答案

在某些Coroutines are launched的上下文中,使用launch协程生成器生成CoroutineScope:

fun test() = CoroutineScope(Dispatchers.Main).launch {
}
launch-是 CoroutineScope对象上的 extension function,它是 defined,如下所示:
public fun CoroutineScope.launch(...): Job {}
runBlocking-不是扩展函数,因此可以将其称为常规函数,它是 defined,如下所示:
public fun <T> runBlocking(...): T {}

关于android - 对Kotlin协程感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62402345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com