【问题标题】:Migrate to Kotlin coroutines in Android with Kotlin 1.3使用 Kotlin 1.3 在 Android 中迁移到 Kotlin 协程
【发布时间】:2018-10-24 20:10:42
【问题描述】:

我应该在我的 build.gradle 文件中更改什么或导入类以在我的带有 Kotlin 1.3 的 Android 项目中使用稳定的协程函数?

我的build.gradle中关于协程的片段

implementation "org.jetbrains.kotlin:kotlin-coroutines-core:$coroutines_version" implementation "org.jetbrains.kotlin:kotlin-coroutines-android:$coroutines_version"

当然我用的是Android Studio 3.3 Preview

【问题讨论】:

  • Kotlin 1.3 尚未发布。如果你想要 Kotlin 1.3,你必须使用 EAP
  • 我正在使用它,但我认为我没有正确迁移到 Kotlin 1.3。我在 gradle "library should be updated to be compatible with kotlin 1.3" 中实现协程库时出错
  • 我找不到任何信息什么版本是正确的。
  • 添加http://dl.bintray.com/kotlin/kotlin-eap。当前的 Kotlin 是 1.3.0-rc-190。确保你也更新了 Kotlin 插件。另外,它是org.jetbrains.kotlinx:kotlinx-coroutines-coreorg.jetbrains.kotlinx:kotlinx-coroutines-android
  • 感谢 Joshua 的回复!我的队友帮助我找到了解决方案。我不得不将协程版本增加到 1.0.0-RC1

标签: android kotlin kotlinx.coroutines


【解决方案1】:

build.gradle 中将库更改为

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'.

删除,如果已添加:

kotlin {
    experimental {
        coroutines "enable"
    }
}

在代码中将launch 更改为GlobalScope.launch(Dispatchers.IO)GlobalScope.launch(Dispatchers.Main)

更新

请使用本地协程上下文而不是全局范围(例如,参见http://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html)。

对于活动

https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md

实现CoroutineScope:

class YourActivity : AppCompatActivity(), CoroutineScope {

添加一个局部变量job并对其进行初始化:

private lateinit var job: Job

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    job = Job()
}

创建协程上下文并在 Activity 销毁时将其取消:

override fun onDestroy() {
    job.cancel()
    super.onDestroy()
}

override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

Fragment(同Activity

实现 CoroutineScope:

class YourFragment : Fragment(), CoroutineScope {

创建一个局部变量job并在onCreate()中初始化它。 (我尝试写private val job: Job = Job(),但遇到问题,在ViewPager 中,您将创建Fragments 和他们的工作。因为我们将在onDestroy() 中刷卡时取消jobViewPager,我们应该重新创建作业)。

private lateinit var job: Job

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    ...
    job = Job()
}

创建协程上下文并在 Fragment 销毁时将其取消:

override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job // You can use different variants here. 

override fun onDestroy() {
    job.cancel()
    super.onDestroy()
}

启动示例

照常使用launch

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    launch {
        // Wait for result of I/O operation without blocking the main thread.
        withContext(Dispatchers.IO) {
            interactor.getCountry().let {
                countryName = it.name
            }
        }

        // Update views in the UI thread.
        country.updateCaption(countryName)
    }
}

在我的例子中,当我使用带有常规回调的 API 请求时出现了问题。尚未调用回调中的 launch 内部。所以我用交互器重写了那个代码。

【讨论】:

    【解决方案2】:

    我的队友帮助我找到了解决方案。我不得不将协程版本增加到 1.0.0-RC1。对于可能不知道使用 Android 协程的变化的每个人:

    • 我不得不将协程的 UI 上下文更改为 Dispatchers.Main
    • 我使用旧的实验性协程版本(可能是 0.23),所以对于不知道的每个人 - 现在已弃用启动,您应该改用结构化并发(例如 coroutineScope)。
    • 现在异步函数不能在范围之外运行。

    我希望我能帮助别人。不要浪费时间。编程愉快!

    【讨论】:

      【解决方案3】:

      实现版本必须>=测试版本

      build.gradle (:mobile)

      dependencies {
          implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines")
      
          // Testing
          testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"
          androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"
      }
      

      build.gradle(项目)

      buildscript {
          ...
          ext.coroutines = '1.3.6'
      }
      

      故障修复

      FAILURE: Build failed with an exception.
      
      * What went wrong:
      Could not determine the dependencies of task ':app:processDebugAndroidTestManifest'.
      > Could not resolve all task dependencies for configuration ':app:debugAndroidTestRuntimeClasspath'.
          > Could not resolve org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5.
          Required by:
              project :app
           > Cannot find a version of 'org.jetbrains.kotlinx:kotlinx-coroutines-core' that satisfies the version constraints:
                Dependency path 'Open Weather:app:unspecified' --> 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5'
      

      GL

      【讨论】:

        【解决方案4】:

        只需将“mavenCentral()”添加到 build.gradle 波纹管构建脚本:我已使用此修复。

        buildscript {
            ext.kotlin_version = '1.3.72'
        
            repositories {
                google()
                jcenter()
        
            }
            dependencies {
                classpath 'com.android.tools.build:gradle:4.0.0'
                classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
                // NOTE: Do not place your application dependencies here; they belong
                // in the individual module build.gradle files
            }
        }
        
        allprojects {
            repositories {
                google()
                mavenCentral() //Add this Line only <<<<<<<<<<<<<<<<<<
            }
        }
        

        【讨论】:

        • 感谢mavenCentral() allprojects repositories!我将jcenter() 替换为maven(),因为jCenter 将在五月关闭。
        猜你喜欢
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多