kotlin-coroutineskotlin-multiplatformkmpkotlin-desktop

Dispatchers.Main was accessed when the platform dispatcher was absent kmp


my problem is: Dispatchers.Main was ccessed when the platform dispatcher was absent and the test deispatcher was unset. Please make sure Dispatchers.setMain() is called before accessing Dispatcher.Main and that Disaptchers.Main is not accessed after Dispatchers.resetMain(). Write my app on kmp, target platfroms are android and desktop. Error comes only on desktop, in android all works fine.

Module code:

val dispatchersModule = module {
    single {
        Dispatchers.IO
    }
}

ViewModel code:

class MangaScreenVM(
    private val repository: MangaScreenRepo,
    private val dispatcherIo: CoroutineDispatcher
): ViewModel() {
    //Something like a custom paging :)
    private val _allManga = MutableStateFlow<List<MangaByTitleData>>(emptyList())
    val allManga = _allManga.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5_000),
        emptyList()
    )

    private val limit = 20
    private var offset = 0

    fun fetchAllManga() {
        viewModelScope.launch(dispatcherIo) {
            val response = repository.getMangaByTitle(offset = offset, limit = limit)
            response.onError { error ->
                SnackbarController.sendEvent(
                    SnackbarEvent(
                        message = processNetworkErrorsForUi(error),
                        action = SnackbarAction(
                            name = "Refresh",
                            action = { fetchAllManga() }
                        )
                    )
                )
            }
            response.onSuccess { data ->
                _allManga.value += data.data
                offset += limit
            }
        }
    }
}

Before this problem was another: Module with the Main dispatcher had failed to initialize, but i solved it by adding this: kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } to my toml and gradle file


Solution

  • Okay, finally i solve this problem. What i do:

    libs.toml:

    kotlinx-coroutines = "1.10.1" kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }

    gradle:

    implementation(libs.kotlinx.coroutines.test)

    main.kt(desktop app):

    Dispatchers.setMain(Dispatchers.Swing)