Home » Android » Unresolved reference: viewModelScope – Kotlin Android

Unresolved reference: viewModelScope – Kotlin Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I try to add viewModelScope to a basic viewModel but android studio doesn’t recognize it.

I tried to change my gradle build file with some solution I found but nothing works.

Here an extract of my build.gradle app

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha01"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01"
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0-alpha01"

When I type viewModelScope in my viewModel it say Unresolved reference: viewModelScope.

How to&Answers:

for now its in alpha, so please update your gradle to use the following dependencies:

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01"

Answer:

I’ve had the same issue and I’ve just imported:

"androidx.navigation:navigation-fragment-ktx:2.2.0-rc03"
"androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-rc03"

Even though I thought fragment-ktx was not really related. Took me a while to figure that out. Hope it helps!

Answer:

It looks like you’ve got two different versions of the androidX lifecycle libraries in use.

Change your app/build.gradle to be:

...
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha01"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0-alpha01"
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0-alpha01"
...

Answer:

For latest version of the artifact refer
Maven Repository Android Lifecycle ViewModel Kotlin Extensions

In app level build.gradle file add the following :-

def lifecycle_version = "2.2.0-rc03"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

Don’t forget to add apply plugin: 'kotlin-kapt' at the top of app/build.gradle file