问题
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'
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?
回答1:
Using just the kotlinx-coroutines-android version solves the problem.
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.1'
回答2:
You may be missing some Proguard rules.
I had the same problem in release build and solved it by adding the following rules:
-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {}
-keepclassmembernames class kotlinx.** {
volatile <fields>;
}
from https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-android/example-app/app/proguard-rules.pro
回答3:
./gradlew assembleDebug --rerun-tasks
fixes it if the above answers don't work for you (because you already had the required dependencies and you are using R8 which does not need the proguard rules).
回答4:
Try to clean
the project and rebuild
.
if not worked then try:
File -> invalidate Caches / Restart...
来源:https://stackoverflow.com/questions/52677638/module-with-main-dispatcher-is-missing