5

I'm trying to use the new viewModelScope() function provided by the new android ktx library.

In the gradle file, I've added:

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
implementation 'androidx.core:core-ktx:1.0.2'

but when I tied to access the viewModelScope(), I got Unresolved reference: viewModelScope error:

class MainViewModel(application: Application): AndroidViewModel(application) {

    fun fetchData(){
        viewModelScope.launch{

        }
    }
}

I don't understand what the problem is. Any idea? Thanks.

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
Toni Joe
  • 7,715
  • 12
  • 50
  • 69

2 Answers2

6

Check the release notes https://developer.android.com/jetpack/androidx/releases/lifecycle#declaring_dependencies

viewModelScope is available from v2.1.x

So you need to bump your version in your gradle file.

veritas1
  • 8,740
  • 6
  • 27
  • 37
2

I have use in my project 2.1.0-beta01:

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

This is less version then released on official site.
However, I use it because new version 2.2.0-alpha01 still has the Unresolved reference: viewModelScope - Android KTX error.

V.March
  • 1,820
  • 1
  • 21
  • 30