As ViewModelProviders.of() is deprecated, how should I create object of ViewModel in the Activity?

53 Views Asked by At
error: cannot find symbol
        MainActivityViewModel model = ViewModelProvider(this).get(MainActivityViewModel.class);

I tried different solutions available but no luck for me.

1

There are 1 best solutions below

0
Qing On

You can create a view model using the by ViewModels() kotlin property delegate:

private val viewModel: YourCustomViewModel by viewModels()

or you can use ViewModelProvider to create ViewModels and retain them in a store of the given ViewModelStoreOwner.

Check the official documentation for best practices: https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders#of(androidx.fragment.app.Fragment) https://developer.android.com/reference/androidx/lifecycle/ViewModelProvider#ViewModelProvider(androidx.lifecycle.ViewModelStoreOwner)