仅在发布 APK 中出现异常 "Module with the Main dispatcher is missing."

Exception "Module with the Main dispatcher is missing." in release APK only

我在 Android 项目中使用 Kotlin 1.3 EAP 和 kotlinx-coroutines-android:1.0.0-RC1。我的开发构建成功,应用程序运行良好。但是,当我 Generate Signed APK 时,该应用程序仍在构建和运行,但随后因

而崩溃

java.lang.IllegalStateException: Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android'

由于开发构建运行良好,显然 gradle 文件中没有遗漏。我有这些设置:

项目 build.gradle:

buildscript {
    ext.kotlin_version = '1.3.0-rc-190'
    ....

模块 build.gradle:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0-RC1'

随着时间的推移,同一个应用已经运行多个不同版本的实验性协程,这是我第一次遇到这个问题。我怀疑 EAP 工件中存在一些临时问题。

我可以尝试做些什么?

如果您使用混淆器,请添加这些混淆器 rules

# ServiceLoader support
-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {}
-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {}

# Most of volatile fields are updated with AFU and should not be mangled
-keepclassmembernames class kotlinx.** {
    volatile <fields>;
}

Source

将此行添加到您的 PROGUARD 文件中

-保持 class kotlinx.coroutines.android.* {*;}