如何使用新的 androidx.lifecycle:*:2.2.0-alpha01 获得 lifecycle.coroutineScope

How to get lifecycle.coroutineScope with new androidx.lifecycle:*:2.2.0-alpha01

2019 年 5 月 7 日 androidx.lifecycle:*:2.2.0-alpha01 发布公告:

This release adds new features that adds support for Kotlin coroutines for Lifecycle and LiveData. Detailed documentation on them can be found here.

documentation 上提到我可以获得 LifecycleScope:

either via lifecycle.coroutineScope or lifecycleOwner.lifecycleScope properties

但我似乎找不到 none 个。我当前的依赖项是:

def lifecycle_ver = "2.2.0-alpha01"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_ver"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_ver"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_ver"

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1'

可能是什么原因以及如何获取这些 api?

我实际上花了几个小时试图自己解决这个问题,结果发现它在一个只存在于 alpha 版中的新包中。添加这个,你应该可以开始了。

implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_ver"

接受的答案有效,但我是第一次被误用,所以我想说清楚,lifecycle的当前版本是"2.1.0"lifecycleScope,并且 ViewModelScope 在这个版本中不可用,让他们使用

对于 ViewModelScope,请使用 androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 或更高版本。

对于 LifecycleScope,请使用 androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 或更高版本。

此时2.3.0-rc01可用。