对Kotlin协程感到困惑

时间:2020-06-16 06:37:11

标签: android kotlin kotlin-coroutines

这没有编译错误:

suspend fun test() {
    runBlocking {

    }
}

这有一个编译错误:

suspend fun test() {
    launch {

    }
}

未解决的参考。以下候选人均不适用 由于接收器类型不匹配:公共乐趣 CoroutineScope.launch(上下文:CoroutineContext = ...,开始: CoroutineStart = ...,块:挂起CoroutineScope。()-> Unit):作业 在kotlinx.coroutines中定义

我不太明白问题出在哪里...

1 个答案:

答案 0 :(得分:1)

Coroutines are launchedlaunch协程生成器在某些CoroutineScope的上下文中:

fun test() = CoroutineScope(Dispatchers.Main).launch {
}

launch-是CoroutineScope对象上的extension function,它是defined,如下所示:

public fun CoroutineScope.launch(...): Job {}

runBlocking-不是扩展函数,因此可以将其称为常规函数,它是defined,如下所示:

public fun <T> runBlocking(...): T {}