Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference: viewModelScope - Kotlin Android

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.

like image 746
LopsemPyier Avatar asked May 25 '19 14:05

LopsemPyier


4 Answers

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

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
like image 65
j2emanue Avatar answered Nov 07 '22 07:11

j2emanue


In my case i forgot to extends ViewModel in that class, the class you use for viewModelScope must be like yourModelClass : ViewModel() in kotlin and for java yourModelClass extends ViewModel

Hope its help

like image 42
lukman nudin Avatar answered Nov 07 '22 07:11

lukman nudin


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!

like image 8
Fernando Prieto Moyano Avatar answered Nov 07 '22 08:11

Fernando Prieto Moyano


Also check that you are in the correct file. I had the same problem for a moment and I came to this page, but later on, I realized I accidentally tried to run viewModelScope.launch on my Fragment.

viewModelScope.launch is only available in your ViewModels and lifecycleScope.launch in your lifecycle aware components.

like image 4
ilker Avatar answered Nov 07 '22 07:11

ilker