尝试构建一个在 Activity 中使用kotlin协程的简单示例:

   lifecycleScope.launch {
             val result = httpGet("http://hmkcode-api.appspot.com/rest/api/hello/Android")
              textView.setText(result)
   }

无法摆脱错误“ Unresolved reference lifecycleScope”

gradle文件的相关部分:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'



dependencies {

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:1.3.2"

def androidArchVersion = '1.1.1'
implementation "android.arch.lifecycle:viewmodel:$androidArchVersion"
implementation "android.arch.lifecycle:livedata:$androidArchVersion"
annotationProcessor "android.arch.lifecycle:compiler:$androidArchVersion"
testImplementation "android.arch.core:core-testing:$androidArchVersion"
implementation "android.arch.lifecycle:extensions:$androidArchVersion"
}

kotlinOptions {
    jvmTarget = '1.8'
    apiVersion = '1.3'
    languageVersion = '1.3'
}

}

最佳答案

根据Lifecycle KTX documentation,如果要特定于协程的扩展,则必须包括lifecycle-runtime-ktx Artifact 。

请注意,lifecycle-runtime-ktx仅在Lifecycle 2.2.0中引入,因此您需要Migrate to AndroidX,然后如果要使用该功能,请升级到Lifecycle 2.2.0

关于android - 如何解决 Unresolved reference lifecycleScope?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60744043/

10-11 15:00