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中添加了以下内容:

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

我对此还是个新手,有人能帮我一下吗?

推荐答案

只使用kotlinx-coroutines-android版本就解决了这个问题.

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

Kotlin相关问答推荐

如何使用具有名称冲突的限定这个?

Kotlin是否针对范围和进度优化sum()?

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

Kotlin Poet 的导入不明确

Kotlin 如何使用其 get 函数在内部检索映射值

如果带注释的成员未被特定块包围,则发出 IDE 警告

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

为空数组添加值

interface扩展

如何通过反射使用 Kotlin 对象

空对象引用上的 TransitionSet ArrayList.size()

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

在android的默认浏览器 Select 列表中添加我的浏览器?

Kotlin类型安全类型别名

尾随 lambda 语法(Kotlin)的目的是什么?

如何修复未解析的参考生命周期范围?

Kotlin for assertThat(foo, instanceOf(Bar.class))

Dagger 2 androidx fragment不兼容类型