kotlinandroid-jetpackandroid-viewmodelviewmodelproviders

ViewModelProviders is deprecated in 2.2.0


Currently I update androidx.lifecycle:lifecycle-extensions version from 2.2.0-alpha01 to 2.2.0and it shows that ViewModelProviders is depricated. So what is the alternative way to use ViewModelProviders in kotlin?


Solution

  • As it says in the documentation, you can now simply use the ViewModelProvider constructors directly. It should be mostly a matter of changing ViewModelProviders.of( to ViewModelProvider(, but you can see the complete listing of exactly which new methods correspond to which old ones in the documentation as well.

    In Kotlin, you can also use the by viewModels() property delegate within your Activity/Fragment to get individual ViewModels. For example:

    val model: MyViewModel by viewModels()