缺少主调度程序的模块

新手上路,请多包涵

我正在尝试对我的本地数据库进行后台调用,并使用协同程序使用结果更新 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'

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

原文由 Khongor Bayarsaikhan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

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

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

原文由 Khongor Bayarsaikhan 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可能缺少一些 Proguard 规则

我在发布版本中遇到了同样的问题,并通过添加以下规则解决了它:

 -keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {}
-keepclassmembernames class kotlinx.** {
    volatile <fields>;
}

来自 https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-android/example-app/app/proguard-rules.pro

原文由 Ganesh Kanna 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题