androidkotlinandroid-ktx

Unresolved reference: viewModelScope - Android KTX


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.


Solution

  • 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.