【发布时间】: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) 并且它可以工作,但这不是我需要的。