Has anyone found a way to force reinitiation of a ...
# android
j
Has anyone found a way to force reinitiation of a viewmodel?
s
What does ‘reinitiation’ mean? What are you trying to accomplish?
j
Destroy the existing instance and create a new one
I’m looking for a way to destroy a viewmodel without destroying the Application
s
what I mean is why? What would that accomplish? e.g: You need to reclaim resources? You need to observe again from a LiveData?
j
I need to recreate it with new arguments and clear all its values
s
Clearing state should not require recreating it. Can you not just modify state as desired? The whole point of a ViewModel is that it can exist independently of an activity’s/fragment’s LifeCycle.
j
Clearing all the values would be simple yes, I’m mainly looking for how to recreate it with new arguments
s
I see no reason for recreating a ViewModel when you can just change any of those arguments as part of it’s state. Perhaps the arguments you have on the constructor shouldn’t be provided there?
b
iirc there is no clear way to do this, BUT there is hack that allows you to drop an old VM - if you look at ViewModelProvider source code (you need #get(key, class) fun), it only overrides VM in store if a new class doesn't match previously created VM's class. So you can play around it - create FakeViewModel with the same key, then you will be able to recreate your VM again.
But I don't recommend doing this 🙂
j
Hmm I wouldn’t want to do that 🙁
But thanks for the tip
s
If you want to recreate ViewModel, don't use ViewModelProvider, just create ViewModel object and manage it by yourself. But I'm not recommend 🙂