ViewModel in Kotlin: Unresolved Reference

RedBassett picture RedBassett · Apr 20, 2018 · Viewed 14.9k times · Source

I am trying to implement ViewModel in a 100% Kotlin app. Every piece of documentation I can find says I want to use this to get the ViewModel instance:

ViewModelProviders.of(this).get(CustomViewModel::class.java)

According to the docs, I should be able to import this with:

import android.arch.lifecycle.ViewModelProviders

This import is unresolved though. I am using the following in my build file:

def androidArchVersion = '1.1.1'
implementation "android.arch.lifecycle:viewmodel:$androidArchVersion"
implementation "android.arch.lifecycle:livedata:$androidArchVersion"
annotationProcessor "android.arch.lifecycler:compiler:$androidArchVersion"
testImplementation "android.arch.core:core-testing:$androidArchVersion"

Why can't I access ViewModelProviders?

Answer

Supriya picture Supriya · Apr 20, 2018

Include the following as a dependency:

implementation "android.arch.lifecycle:extensions:1.1.1"

This dependency is for both ViewModel and LiveData and thus would not require you to give separate dependencies for the same either; i.e. the first two dependencies indicated by you can be replaced by the aforementioned lifecycle extensions dependency.