kotlin 协程启动在lambda中不起作用

gijlo24d  于 12个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(124)

我有一段代码:

fun main(args: Array<String>) = runBlocking {
    val scope = CoroutineScope(this.coroutineContext + SupervisorJob())
    val requestLooper = RequestLooper()
    val messageParser = MessageParser(
        onStart = { chatId ->
            println("On text")
            scope.launch {
                println("Enter coroutine")
                requestLooper.start(chatId)
            }
            println("On text exit")
        },
        onStop = { chatId -> requestLooper.stop(chatId) }
    )
}

在这段代码中,我在每个lambda调用上启动一个新的协程。
这段代码的输出是:

On text
On text exit

正如你所看到的,发射根本不起作用。你能告诉我为什么吗?

w41d8nur

w41d8nur1#

结果我不能直接从lambda启动协程。我需要创建一个作用域并在lambda中使用它。就像这样:

fun main(args: Array<String>) = runBlocking {
    val scope = CoroutineScope(this.coroutineContext + SupervisorJob())

    val requestLooper = RequestLooper()
    val messageParser = MessageParser(
        onStart = { chatId ->
            scope.launch {
                requestLooper.start(chatId)
            }
        },
        onStop = { chatId -> requestLooper.stop(chatId) }
    )
}

重要的部分是:

val scope = CoroutineScope(this.coroutineContext + SupervisorJob())
...
scope.launch {
...

相关问题