Reputation: 1226
I'm trying to use ViewModel
, for saving data to share between Fragments
. That is it:
class AnimalViewModel : ViewModel() {
private var data = MutableLiveData<AnimalWithHints>()
fun setData(animalData: AnimalWithHints) {
data.value = animalData
Timber.e("Saved?")
}
fun getData(): LiveData<AnimalWithHints> {
if (data.value == null) {
Timber.e("Null?")
data.value = AnimalWithHints()
}
return data
}
}
So I've filled non-null object (checked it) and I write before transaction:
ViewModelProviders.of(this).get(AnimalViewModel::class.java).setData(animalWithHints)
I see "Saved?" when it happens, so I think save working good. I logged some field of AnimalWithHints
, and I saw it was correct.
Then I try to get my object:
val animalWithHints = ViewModelProviders.of(this).get(AnimalViewModel::class.java).getData().value
And I see "Null?". And it's true, data.value
is rly new empty AnimalWithHints
object.
Strange thing is I have only two lines of code, using ViewModel
. I only save and get object, there is no place when I can clear it or modify somehow.
I need you help to understand what's wrong.
Upvotes: 1
Views: 135
Reputation: 12118
When you want to share data between your Fragments
that are in same Activity
, you'll need to create instance of ViewModel
with context to Activity
.
Below syntax provides you instance of ViewModel
that is at Fragment
level only (You can share it at Fragment itself with some child fragments inside of that Frament):
ViewModelProviders.of(this@Fragment)[SomeViewModel::class.java] // This will give you view model at fragment level
While passing Activity
object to your ViewModelProvider
inside your Fragment
gives you ViewModel
at Activity
level. Hence You're having multiple Fragments inside same Activity
meaning context of Activity is same gives your same ViewModel
object at both Fragments
.
So for sharing ViewModel
between fragments, use below syntax :
ViewModelProviders.of(activity)[SomeViewModel::class.java] // This will provide you shared view model across multiple fragments.
Upvotes: 1