2

I am using

    class MyViewModelFactory(
    private val app: Application,
    private val someClass: SomeClass,
       ) : ViewModelProvider.Factory {
    @Suppress("unchecked_cast")
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MyViewModel::class.java)) {
            return MyViewModel(application, someClass) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
  }

And

viewModel = ViewModelProvider(this, MyViewModelFactory(application, someClass)).get(
        MyViewModel::class.java
    )

But every time when the fragment instantiated, new viewmodel is created, instead of to return existing viewmodel.

Pavel Poley
  • 5,307
  • 4
  • 35
  • 66
  • That would seem to be the expected behavior. The only time that you would get an existing viewmodel is on a configuration change or if your scope of the viewmodel is bigger than the fragment (e.g., an activity-scoped viewmodel). – CommonsWare Nov 05 '21 at 11:50
  • 1
    As I remember without factory I am getting existing viewmodel per fragment – Pavel Poley Nov 05 '21 at 11:56
  • Presumably, you changed your viewmodel scope. – CommonsWare Nov 05 '21 at 12:00

0 Answers0