How to get lifecycle.coroutineScope with new andro

2020-06-30 23:15发布

问题:

On 7th May, 2019 androidx.lifecycle:*:2.2.0-alpha01 was released announcing:

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

On documentation it's mentioned that I can get the LifecycleScope:

either via lifecycle.coroutineScope or lifecycleOwner.lifecycleScope properties

But it seems that I'm not able to find none of them. My current dependencises are:

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'

What may be the cause and how do get these apis?

回答1:

I actually spent a couple hours trying to figure this out myself and it turns out it is in a new package that only exists as of the alpha. Add this and you should be good to go.

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


回答2:

The accepted answers is working, but I'm misused for the first time, so I'm trying to make it clear, the current version of lifecycle is "2.1.0" and lifecycleScope, and ViewModelScope is not available in this version, to get them use

For ViewModelScope, use androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 or higher.

For LifecycleScope, use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01 or higher.

at this time "2.3.0-alpha01" is available