【问题标题】:Kotlin coroutines not running launch on mainKotlin 协程未在 main 上运行启动
【发布时间】:2019-12-30 09:01:40
【问题描述】:

我有以下代码:

 Timber.d("Calling coroutine from thread: ${Thread.currentThread().name}")
    scope.launch {
        Timber.d("Current thread: ${Thread.currentThread().name}")
        runTest()
    }

 suspend fun runTest() {
    coroutineScope {
        launch(Dispatchers.Main) {
            Timber.d("Running from thread: ${Thread.currentThread().name}")
        }
    }
}

如果我运行它。应用程序崩溃,日志中没有错误。 在我的日志中我看到:

从线程调用协程:main

当前线程:DefaultDispatcher-worker-2

但我没有看到带有 Running from thread:

的条目

这是在视图模型中完成的 我的范围如下所示:

val scope: ViewModelCoroutineScope = ViewModelCoroutineScope(Dispatchers.Default)

class ViewModelCoroutineScope(
    context: CoroutineContext
) : CoroutineScope {

    private var onViewDetachJob = Job()
    override val coroutineContext: CoroutineContext = context + onViewDetachJob

    fun onCleared() {
        onViewDetachJob.cancel()
    }
}

我做错了什么?

【问题讨论】:

  • 我刚刚试过你的代码,它工作正常。 Calling coroutine from thread: mainCurrent thread: DefaultDispatcher-worker-1Running from thread: main
  • 我已经把它移到了另一个地方,但仍然遇到同样的问题。我尝试将 launch(Dispatchers.Main) 切换为 launch(Dispatchers.Default) 并且它可以工作,但这不是我需要的。

标签: kotlin kotlin-coroutines


【解决方案1】:

移动到另一台机器上,我终于收到了一些关于 Dispatchers.MAIN 无法正常工作的错误。

最后我所要做的就是将所有原始协程依赖替换为:

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1")

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2019-12-18
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2022-11-08
    相关资源
    最近更新 更多