Search code examples
androidandroid-viewmodel

Getting ViewModel Instance by ViewModelProvider


ViewModelProviders is deprecated

ViewModelProviders.of(this).get(MyViewModel::Class.java)

As suggested by other StackOverflow answers and This is not being found:

ViewModelProvider(this).get(MyViewModel::class.java)

There seems to be a problem with onCleared() not being called in:

ViewModelProvider.NewInstanceFactory().create(MainViewModel::class.java)

Also, I don't want to use KTX-Extensions by viewmodel()

The last option is:

ViewModelProvider(this, myViewModelFactory).get(MyViewModel::class.java)

which needs a ViewModelFactory that I haven't figured how to implement and return the instance:

class ViewModelFactory : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        ...
    }

}

It's been a long time I've been injecting my ViewModels by using Koin and not using it makes it confusing to get an instance of a ViewModel.

Is there any way to get an instance of ViewModel easily in API Level 30?


Solution

  • This is completely gone from API 30

    "API 30" refers to an Android SDK framework version. ViewModelProviders was never in the framework. ViewModelProviders still exists in lifecycle-extensions and is still documented. You are correct that it is deprecated.

    This is also gone

    No, it is not. It is available in lifecycle-viewmodel and is still documented.

    Is there any way to get an instance of ViewModel easily in API Level 30?

    Use ViewModelProvider(this).get(MyViewModel::class.java) (your second code snippet). See this Java example (in Kotlin, I use a property delegate, either Google's or Koin's).