Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
12.98k stars 1.84k forks source link

Module with the Main dispatcher had failed to initialize #932

Closed marenovakovic closed 2 years ago

marenovakovic commented 5 years ago

Getting this error on android. coroutiens version 1.0.0 java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:79) at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:54) at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:373) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25) at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:160) at kotlinx.coroutines.channels.ActorKt.actor(Actor.kt:121) at kotlinx.coroutines.channels.ActorKt.actor$default(Actor.kt:112)

qwwdfsad commented 5 years ago

Please update to 1.1.0 and see if it still reproduces. Also, it is useful to provide full stacktrace (this exception should have a meaningful cause) and some context.

webfrea-k commented 5 years ago

Had the same issue in 1.0.1, point of crash: private val uiScope = CoroutineScope(Dispatchers.Main) uiScope.launch {} -> Crash The issue is resolved in version 1.1.0

marenovakovic commented 5 years ago

Upgrading to 1.1.0 solved it. Android Studio haven't showed there is newer version, hm. Thanks.

JabezNzomo99 commented 5 years ago

Upgrading to 1.1.0 solved it for me as well. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0

Jeff11 commented 5 years ago

This still happens on kotlinx-coroutines-android:1.1.1 80% Android 6.0.x, 20% Android 5.1 Unfortunately I couldn't reproduce on a Samsung S5 test device.

Fatal Exception: java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize
       at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:79)
       at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:54)
       at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:373)
       at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25)
       at kotlinx.coroutines.CoroutineStart.invoke(AbstractCoroutine.kt:109)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Unknown Source:54)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default$28f1ba1(Builders.common.kt:47)
       at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1)
       at my.app.NotesFragment.loadSomething(NotesFragment.kt:542)
       at my.app.NotesFragment.onCreateView(NotesFragment.kt:101)
       at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2530)
...
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by java.util.ServiceConfigurationError: Couldn't read jar:file:/data/app/my.app-1/base.apk!/META-INF/services/kotlinx.coroutines.internal.MainDispatcherFactory
       at java.util.ServiceLoader$ServiceIterator.readClass(ServiceLoader.java:245)
       at java.util.ServiceLoader$ServiceIterator.hasNext(ServiceLoader.java:202)
       at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1145)
       at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1178)
       at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1169)
       at kotlinx.coroutines.internal.MainDispatcherLoader.loadMainDispatcher(MainDispatchers.kt:15)
       at kotlinx.coroutines.internal.MainDispatcherLoader.(MainDispatchers.kt:10)
       at kotlinx.coroutines.Dispatchers.getMain(Dispatchers.kt:55)
       at my.app.MainCoroutineScope$DefaultImpls.getCoroutineContext(MainCoroutineScope.kt:9)
       at my.app.NotesFragment.getCoroutineContext(NotesFragment.kt:64)
       at kotlinx.coroutines.CoroutineContextKt.newCoroutineContext(CoroutineContext.kt:57)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Unknown Source:50)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default$28f1ba1(Builders.common.kt:47)
       at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1)
       at my.app.NotesFragment.loadSomething(NotesFragment.kt:542)
       at my.app.NotesFragment.onCreateView(NotesFragment.kt:101)
       at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2530)
...
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by java.util.ConcurrentModificationException
       at java.util.HashMap$HashIterator.nextEntry(HashMap.java:788)
...
       at java.util.ServiceLoader$ServiceIterator.hasNext(ServiceLoader.java:202)
       at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1145)
       at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1178)
       at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1169)
       at kotlinx.coroutines.internal.MainDispatcherLoader.loadMainDispatcher(MainDispatchers.kt:15)
       at kotlinx.coroutines.internal.MainDispatcherLoader.(MainDispatchers.kt:10)
       at kotlinx.coroutines.Dispatchers.getMain(Dispatchers.kt:55)
       at my.app.MainCoroutineScope$DefaultImpls.getCoroutineContext(MainCoroutineScope.kt:9)
       at my.app.NotesFragment.getCoroutineContext(NotesFragment.kt:64)
       at kotlinx.coroutines.CoroutineContextKt.newCoroutineContext(CoroutineContext.kt:57)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Unknown Source:50)
       at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default$28f1ba1(Builders.common.kt:47)
       at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1)
       at my.app.NotesFragment.loadSomething(NotesFragment.kt:542)
       at my.app.NotesFragment.onCreateView(NotesFragment.kt:101)
       at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2530)
...
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
oarostovtseva commented 5 years ago

Agree, still reproducible with kotlinx-coroutines-android:1.1.1

mochadwi commented 5 years ago

@oarostovtseva @Jeff11 try this: https://github.com/Kotlin/kotlinx.coroutines/blob/39c7ca5eb931d25fa06fea2171b1be17a5490a15/core/kotlinx-coroutines-core/resources/META-INF/proguard/coroutines.pro

dendrocyte commented 5 years ago

The same here. kotlinx-coroutines-android:1.1.1 still have this issue

dendrocyte commented 5 years ago

@mochadwi In my case, I have to use this -keepnames class kotlinx.coroutines.internal.MainDispatcherFactory { ; } -keep class kotlinx.coroutines.android.AndroidExceptionPreHandler { ; } -keep class kotlinx.coroutines.android.AndroidDispatcherFactory { ; } -keepnames class kotlinx.coroutines.CoroutineExceptionHandler {;} -keepclassmembernames class kotlinx.** { volatile ; }

AndroidExceptionPreHandler and AndroidDispatcherFactory have to use "keep" not "keepnames" otherwise it will cause another exception about lack of this dependency.

in kotlinx-coroutines-android:1.1.1: it still has issue, if I would like to resign the apk in google play store.

ezamelczyk commented 5 years ago

@qwwdfsad please reopen this issue as it still persists.

qwwdfsad commented 5 years ago

I am reopening the issue to make it easier to find. But there is not much we can do from our side, this is an Android toolchain issue and it should be reported to Google bug tracker

firelonely commented 5 years ago

Please add implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:version" the version as same as implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:version" I do this, solved it. it maybe help you.

liangsaifei commented 5 years ago

Please add implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:version" the version as same as implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:version" I do this, solved it. it maybe help you.

thanks a lot

techartist commented 5 years ago

Please add implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:version" the version as same as implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:version"

and both versions are 1.1.1

Solved it for me.

MrJorgeXavier commented 4 years ago

Even with both coroutines-core and coroutines-android modules being in the same version, the problem persist for me.

giovankabisano commented 4 years ago

Very lack of context here... If you got this error in the implementation code file, you just simply update the coroutines version and it works. If you got this error in the test file (error should be like this A test rule to allow testing coroutines that use the main dispatcher. Without this you'd run into "java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used" ). You can simply add coroutines rule. You can see the code in here https://gist.github.com/AniketSK/0fd48da9ed969eee307f92457115612a

dwitio123 commented 4 years ago

Please add implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:version" the version as same as implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:version" I do this, solved it. it maybe help you.

solved for me, thanks

vsay01 commented 4 years ago

@giovankabisano I have the same issue in test. The problem is that the test pass locally but failed in Jenkin with:

Exception in thread "default" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
    at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:96)
    at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:71)
    at kotlinx.coroutines.test.internal.TestMainDispatcher.isDispatchNeeded(MainTestDispatcher.kt:39)
    at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:420)
    at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:26)
    at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109)
    at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:154)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:54)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47)
    at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source)

Any suggestions ?

parahall commented 4 years ago

Hey folks Posting ti here since it happens to us as well: Hey Folks I'm with AGP 3.6.1 with coroutines 1.3.3 and following R8 rules:

ServiceLoader support

-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {} -keepnames class kotlinx.coroutines.CoroutineExceptionHandler {} -keepnames class kotlinx.coroutines.android.AndroidExceptionPreHandler {} -keepnames class kotlinx.coroutines.android.AndroidDispatcherFactory {}

Most of volatile fields are updated with AFU and should not be mangled

-keepclassmembernames class kotlinx.** { volatile ; }

Same story for the standard library's SafeContinuation that also uses AtomicReferenceFieldUpdater

-keepclassmembernames class kotlin.coroutines.SafeContinuation { volatile ; }

and we faced this exception that is similar to what we have here in bug Fatal Exception: java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MissingMainCoroutineDispatcher.java:95) at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MissingMainCoroutineDispatcher.java:69) at kotlinx.coroutines.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuationKt.java:268) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(CancellableKt.java:26) at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.java:109) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.java:158) at kotlinx.coroutines.BuildersKtBuilders_commonKt.launch(BuildersKt__Builders_commonKt.java:54) at kotlinx.coroutines.BuildersKt.launch(BuildersKt.java:1) at kotlinx.coroutines.BuildersKtBuilders_commonKt.launch$default(BuildersKt__Builders_commonKt.java:47) at kotlinx.coroutines.BuildersKt.launch$default(BuildersKt.java:1) at com.monday.core.BaseTaskRunner.run(BaseTaskRunner.java:100) at com.dapulse.dapulse.refactor.feature.notifications.ui.NotificationListAdapter.handleNewDataPayload(NotificationListAdapter.java:91) at com.dapulse.dapulse.refactor.feature.notifications.ui.NotificationListAdapter.lambda$setupMailBox$0(NotificationListAdapter.java:84) at com.dapulse.dapulse.refactor.feature.notifications.ui.-$$Lambda$NotificationListAdapter$WAZEsTQp9Niqg-cXEd4I8dfwAjA.invoke(-.java:4) at com.dapulse.dapulse.refactor.layers.data.board.mailBox.MailBox$startReceiveMail$1.invokeSuspend(MailBox.java:13) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(BaseContinuationImpl.java:33) at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.java:56) at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:561) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.java:727) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.java:667) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.java:655) Caused by java.lang.ClassCastException: kotlinx.coroutines.android.AndroidExceptionPreHandler cannot be cast to kotlinx.coroutines.internal.MainDispatcherFactory at kotlinx.coroutines.internal.MainDispatcherLoader.loadMainDispatcher(MainDispatcherLoader.java:127) at kotlinx.coroutines.internal.MainDispatcherLoader.(MainDispatcherLoader.java:18) at kotlinx.coroutines.Dispatchers.getMain(Dispatchers.java:58) at com.monday.core.MainThreadTaskRunner.(MainThreadTaskRunner.java:131) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.view.viewPager.NotificationsViewPagerAdapter.(NotificationsViewPagerAdapter.java:32) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.view.NotificationsFragment.initViewPager(NotificationsFragment.java:204) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.view.NotificationsFragment.access$initViewPager(NotificationsFragment.java:41) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.view.NotificationsFragment$setupPresenterObservationsOnCreateView$1.invoke(NotificationsFragment.java:102) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.view.NotificationsFragment$setupPresenterObservationsOnCreateView$1.invoke(NotificationsFragment.java:41) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.viewModel.NotificationsViewModel$observeTabsData$2.onChanged(NotificationsViewModel.java:70) at com.dapulse.dapulse.refactor.feature.notifications.mvpvm.viewModel.NotificationsViewModel$observeTabsData$2.onChanged(NotificationsViewModel.java:14) at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131) at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:144) at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:442) at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:394) at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361) at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:300) at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:339) at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:145) at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:131) at androidx.fragment.app.Fragment.performStart(Fragment.java:2637) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:915) at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830) at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6527) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

cleaning the cache and rebuild solve the issue for now but it's returning time to time in our instrumentation tests on release builds: java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize FATAL EXCEPTION: DefaultDispatcher-worker-1 Process: com.monday.monday, PID: 10833 java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize at rs5.n(MainDispatchers.kt:3) at rs5.b(MainDispatchers.kt:1) at ap5.a(DispatchedContinuation.kt:3) at xs5.a(Unknown Source:8) at sn5.a(AbstractCoroutine.kt:14) at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source:7) at t45.run(TaskRunner.kt:1) at d$l.invoke(NativeSignupPresenter.kt:5) at d$d.invokeSuspend(NativeSignupPresenter.kt:17) at d$d.invoke(NativeSignupPresenter.kt:2) at v45$a.invokeSuspend(TaskRunner.kt:5) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:3) at cp5.run(DispatchedTask.kt:15) at et5.a(CoroutineScheduler.kt:25) at et5$a.run(CoroutineScheduler.kt:15) Caused by: java.lang.ClassCastException: kotlinx.coroutines.android.AndroidExceptionPreHandler cannot be cast to kotlinx.coroutines.internal.MainDispatcherFactory at qs5.a(MainDispatchers.kt:12) at qs5.(MainDispatchers.kt:5) at ep5.a(Dispatchers.kt:1) at l55.(TaskRunner.kt:1) at ly0.get(SignupModule_ProvidePresenter$app_mondayStagingFactory.java:3) at gb5.get(DoubleCheck.java:6) at l03$d.inject(DaggerAppComponent.java:6) at dagger.android.DispatchingAndroidInjector.maybeInject(DispatchingAndroidInjector.java:6) at com.dapulse.dapulse.refactor.regression.signup.SignupTest$$special$$inlined$getSignupDataProviderTestRuleProvider$1$1$1.inject(ActivityUtil.kt:17) at com.dapulse.dapulse.refactor.regression.signup.SignupTest$$special$$inlined$getSignupDataProviderTestRuleProvider$1$1$1.inject(Unknown Source:2) at dagger.android.DispatchingAndroidInjector.maybeInject(DispatchingAndroidInjector.java:6) at com.dapulse.dapulse.DaPulseApp.a(DaPulseApp.java:8) at bv.inject(Unknown Source:2) at zm4.a(UserManager.java:306) at zm4.b(UserManager.java:11) at com.dapulse.dapulse.refactor.feature.native_signup.NativeSignupActivity.onCreate(NativeSignupActivity.java:3) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

tobi512 commented 4 years ago

Just ran into this issue with v1.1.1 of coroutines. Can be fixed by either updating to v.1.3.5 or adding the following ProGuard/R8 rules in case anyone doesn't want to update:

-keepnames class kotlinx.coroutines.android.AndroidExceptionPreHandler {}
-keepnames class kotlinx.coroutines.android.AndroidDispatcherFactory {}

However, updating to 1.3.5 is the preferred solution here!

ron-k commented 4 years ago

I was using coroutines lib version 1.3.0 when encountered this issue. Updating dependency to 1.3.7: implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'

did not solve the problem. Adding the proguard rules suggested above did the job:

-keepnames class kotlinx.coroutines.android.AndroidExceptionPreHandler {}
-keepnames class kotlinx.coroutines.android.AndroidDispatcherFactory {}

So I guess, the fix is doing both update and Proguard rules

AnastasiaRainMaker commented 4 years ago

I am facing this issue in tests. I am using testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.7' and facing the same issue when it worked before the AGP update to 4.0.1 not sure if it is related and also to implementation 'androidx.core:core-ktx:1.3.1' which may be actually it. Tried the pro guard rules but no luck.

Exception in thread "main @coroutine#32" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:113) at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:91) at kotlinx.coroutines.test.internal.TestMainDispatcher.isDispatchNeeded(MainTestDispatcher.kt:39) at kotlinx.coroutines.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:285) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:26) at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:166) at kotlinx.coroutines.BuildersKt.withContext(Unknown Source) at com.heb.ui.menuitem.viewmodel.MenuItemViewModel$onMenuItemReceived$1.invokeSuspend(MenuItemViewModel.kt:72) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56) at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:50)

segunfrancis commented 4 years ago

I have the same issue. My test passed locally but I got this error Exception in thread "main" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:113) at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:91) at kotlinx.coroutines.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:285) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:26) at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56) at kotlinx.coroutines.BuildersKt.launch(Unknown Source) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:49) at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source) I'm using the following dependencies: implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8" testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8"

boylenssen commented 3 years ago

I'm using this:

class MainCoroutineRule : TestWatcher(), TestCoroutineScope by TestCoroutineScope() {

    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
//        Dispatchers.resetMain()
    }
}

I commented Displatchers.resetMain() out, because that felt like it was causing it. starting() and finished() are being called before and after each test, I don't know why this needs to be happing.

Not resetting the dispatchers seems ok for me, it shouldn't be an issue as this should always be like this when I run test

o-nos commented 2 years ago

still have that issue after update to up-to-day version of kotlinx-coroutines-test.

Exception in thread "Test worker" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

no, it can't be used as I see.

why writing a test is soooooo complicated for a simple test? I just need to check a response of a method, and not spend half a day configuring this coroutine issue :/

dkhalanskyjb commented 2 years ago

Hi @o-nos. If you provide a project where this issue reproduces, I can look at it and identify the problem. Alternatively, there are people on Stack Overflow and the Kotlin Slack channel that can help.

ryanholden8 commented 2 years ago

Can someone clarify if this a bug or if MainCoroutineRule is the standard approach?

It seems strange to require this custom code from a random gist to support a very standard view model unit test.

dkhalanskyjb commented 2 years ago

There are two separate issues here: