How to use ViewModelProviders in Kotlin

Its assumed kotlin is in use - Class ViewModelProviders has been deprecated, instead ViewModelProvider can be used. To use this need to add a dependency in app build.gradle something like this -

 implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

Create a view model class -

class MyViewModel: ViewModel(){
}

The same class object can be find from fragment - onCreateView. For example -

class MyFragment: Fragment(){
    ...
    private lateint var myViewModel: MyViewModel
    ...
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
         ...
         myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
         ...

     }

}

For Java

For pre-AndroidX

implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation "android.arch.lifecycle:viewmodel:1.1.0"

For AndroidX

implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0"

In the latest version, ViewModel can be declared as below

MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);

For Kotlin

For pre-AndroidX

implementation 'android.arch.lifecycle:extensions-ktx:1.1.1'
implementation "android.arch.lifecycle:viewmodel-ktx:1.1.1"

For Android

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"

ViewModel declaration

val model = ViewModelProvider(activity)[MyViewModel::class.java]

Refer below link for the latest AndroidX dependency version

Note: For pre-AndroidX, the dependency version will not be updated