https://kotlinlang.org logo
#android
Title
# android
j

John

10/29/2019, 1:35 PM
Has anyone found a way to force reinitiation of a viewmodel?
s

Stephen Edwards

10/29/2019, 1:46 PM
What does ‘reinitiation’ mean? What are you trying to accomplish?
j

John

10/29/2019, 1:47 PM
Destroy the existing instance and create a new one
I’m looking for a way to destroy a viewmodel without destroying the Application
s

Stephen Edwards

10/29/2019, 1:48 PM
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

John

10/29/2019, 1:48 PM
I need to recreate it with new arguments and clear all its values
s

Stephen Edwards

10/29/2019, 1:50 PM
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

John

10/29/2019, 1:51 PM
Clearing all the values would be simple yes, I’m mainly looking for how to recreate it with new arguments
s

Stephen Edwards

10/29/2019, 1:53 PM
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

bezrukov

10/29/2019, 2:00 PM
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

John

10/29/2019, 2:11 PM
Hmm I wouldn’t want to do that 🙁
But thanks for the tip
s

Saulnguyen

10/30/2019, 3:58 AM
If you want to recreate ViewModel, don't use ViewModelProvider, just create ViewModel object and manage it by yourself. But I'm not recommend 🙂