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?
Using just the kotlinx-coroutines-android version solves the problem.
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.30.1'