我正在学习Android中的协程。我有以下代码:
private val scope = CoroutineScope(Dispatchers.Main + job)
operator fun invoke(token: String, callback: TaskCallback) {
scope.launch {
withContext(Dispatchers.IO) { userDataSource.saveApiToken(token) }
callback.onCompleted()
}
}
我原本期望userDataSource.saveApiToken(token)
会在单独的线程中运行,但它在主线程上运行(方法内的Looper.myLooper() == Looper.getMainLooper()
返回 true)。
可能是什么原因?【我的错误】
我正在使用Kotlin插件版本:1.3.11-release-Studio3.2-1 和以下依赖项:kotlinx-coroutines-core:1.0.1和kotlinx-coroutines-android:1.0.1
Thread.currentThread()
返回的是什么? - SergiowithContext(Dispatchers.IO) { Thread.currentThread() }
? - SergioThread[DefaultDispatcher-worker-1,5,main]
。 - Sergio