主调度程序的模块丢失 [英] Module with Main dispatcher is missing

查看:212
本文介绍了主调度程序的模块丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对本地数据库进行后台调用,并使用协程使用结果更新UI. 这是我的相关代码:

I'm trying to make a background call to my local database and update the UI with the results using coroutines. Here is my relevant code:

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())
            }
        })
    }
}

我的问题是我遇到了运行时异常:

My problem is that I get a runtime exception:

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

我已经将它们添加到了我的gradle中:

I already added these to my gradle:

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

对此我有点陌生,有人可以帮我吗?

I'm a bit new to this, can someone help me?

推荐答案

仅使用kotlinx-coroutines-android版本即可解决此问题.

Using just the kotlinx-coroutines-android version solves the problem.

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

这篇关于主调度程序的模块丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆