I am new to mvvm architecture in android. I am passing data from Fragment A to B . I want to store that data in viewmodel in Frag B and use as per necessity. From what I understand is I need to define two such methods in view model
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
And obeserve it in fragment like
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
This is fine because initially the setitem is getting called in oncreate and I am getting the data. But what if I repeatedly need this Item data for several different reasons in fragment at different times,and this data wont change, then how to use the method
getSelected()
Because I use the observer only once and some event like getdata or post data needs to be called in order to fire the event. So how to achieve it.
is it like I need to call the getvalue() method multiple times, through another method ? I am not sure if this is the correct way. Please clarify.
Thanks :)
CodePudding user response:
The .observe
method will not only observe once, it will get triggered every time the livedata changes its value. From what I know there is nothing wrong with calling .getValue()
to obtain the livedata's value, but since you have already set up an observer you could just update your classes' item variable there:
class MyClass{
val myItem: Item
and in onCreate:
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
myItem = item
});
EDIT: to answer your comment, you can use .getValue()
, there is nothing wrong with it. According to the docs:
To ensure that the activity or fragment has data that it can display as soon as it becomes active. As soon as an app component is in the STARTED state, it receives the most recent value from the LiveData objects it’s observing. This only occurs if the LiveData object to be observed has been set.
So when you start your component, in onCreate
you will receive the latest item value, as long as it is set. It doesn't need to have been changed. You will have the same value throughout your component, and if the livedata gets changed, your myItem
will be updated too.
CodePudding user response:
You can use getSelected().getValue()