android – 缺少主调度程序的模块

前端之家收集整理的这篇文章主要介绍了android – 缺少主调度程序的模块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试对我的本地数据库进行后台调用,并使用协同程序使用结果更新UI.
这是我的相关代码
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.Dispatchers.IO
import kotlinx.coroutines.experimental.Dispatchers.Main
import kotlin.coroutines.experimental.CoroutineContext
import kotlin.coroutines.experimental.suspendCoroutine

class Warehousesviewmodel(private val simRepository: SimRepository)
: BaseReactviewmodel<WarehousesViewData>(),CoroutineScope {

private val job = Job()

override val coroutineContext: CoroutineContext
    get() = job + Main

override val initialViewData = WarehousesViewData(emptyList())

override fun onActiveView() {
    launch {
        val warehouses = async(IO) { loadWarehouses() }.await()
        updateViewData(viewData.value.copy(items = warehouses))
    }
}

private suspend fun loadWarehouses(): List<Warehouse> =
    suspendCoroutine {continuation ->
        simRepository.getWarehouses(object : SimDataSource.LoadWarehousesCallback {
            override fun onWarehousesLoaded(warehouses: List<Warehouse>) {
                Timber.d("Loaded warehouses")
                continuation.resume(warehouses)
            }

            override fun onDatanotAvailable() {
                Timber.d("No available data")
                continuation.resume(emptyList())
            }
        })
    }
}

我的问题是我得到一个运行时异常:

java.lang.IllegalStateException: Module with Main dispatcher is missing. Add dependency with required Main dispatcher,e.g. 'kotlinx-coroutines-android'

我已将这些添加到我的gradle中:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.30.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.26.0'

我对此有点新鲜,有人能帮帮我吗?

解决方法

Tim Castelijns说,使用相同的kotlinx-coroutines版本解决了这个问题.所以在我的情况下:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.30.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.1'

猜你在找的Android相关文章