【发布时间】:2021-05-14 11:54:28
【问题描述】:
在我当前的 Android 应用程序中,我正在研究 Duration 与协程延迟功能的使用,如下所示:-
class WorkerTwo(private val context: Context, private val params: WorkerParameters) : CoroutineWorker(context, params) {
@ExperimentalTime
override suspend fun doWork(): Result = coroutineScope {
(0..100 step 30).forEach {
setProgress(workDataOf(PROGRESS to it))
delay(Duration.Companion.seconds(1L)) // CRASH HERE!!!!!!!!!!!!
}
Result.success()
}
}
但是,当我安装并运行我的应用程序时,它会崩溃,如下所示
Caused by: java.lang.NoSuchMethodError: No static method delay-p9JZ4hM(JLkotlin/coroutines/Continuation;)Ljava/lang/Object; in class Lkotlinx/coroutines/DelayKt; or its super classes (declaration of 'kotlinx.coroutines.DelayKt' appears in /data/app/org.research.development.versiononefive-nC90emPcnKpqBIJrwhWkgQ==/base.apk)
at org.research.development.versiononefive.WorkerTwo$doWork$2.invokeSuspend(WorkerTwo.kt:19)
delay 方法名称被修改为 delay-p9JZ4hM,为什么会出现这种情况?
更新
我通过将其添加到我的 gradle 文件来解决此问题
implementation "androidx.work:work-runtime:2.7.0-alpha03"
implementation "androidx.work:work-runtime-ktx:2.7.0-alpha03"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0-RC"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0-RC"
并像这样重构延迟函数调用:-
delay(Duration.seconds(1L)) // CRASH HERE!!!!!!!!!!!!
【问题讨论】:
-
由于 Duration 的后备字段类型(从 Double 到 Long)的底层变化,协程中损坏的
delay(Duration)方法在 Kotlin 1.4.x 和 Kotlin 1.5 之间发生了变化。为此,您需要使用 Kotlin 1.5.0 和协同程序 >= 1.5.0-RC 进行编译,或者使用以前版本的协同程序和 Kotlin 1.4.x。
标签: kotlin