存储后如何从片段中的视图模型中重复调用数据?
How to repeatedly call a data from view model in fragment after storing it?
我是 android 中的 mvvm 架构新手。我正在将数据从 Fragment A 传递到 B 。我想将该数据存储在 Frag B 的视图模型中,并根据需要使用。据我了解,我需要在视图模型中定义两个这样的方法
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
并像
一样在片段中观察它
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
这很好,因为最初是在 oncreate 中调用 setitem 并且我正在获取数据。但是如果我在不同的时间因为几个不同的原因在片段中重复需要这个Item数据,并且这个数据不会改变,那么如何使用方法
getSelected()
因为我只使用了一次观察器,并且需要调用一些事件,如 getdata 或 post data 才能触发事件。那么如何实现呢。
我是否需要通过另一种方法多次调用 getvalue() 方法?我不确定这是否是正确的方法。请说明。
谢谢:)
.observe
方法不仅会观察一次,每次livedata值改变都会触发。据我所知,调用 .getValue()
获取实时数据的值没有任何问题,但由于您已经设置了一个观察者,您可以在那里更新您的 类' 项目变量:
class MyClass{
val myItem: Item
并在 onCreate 中:
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
myItem = item
});
编辑:要回答您的评论,您可以使用 .getValue()
,没有任何问题。根据 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.
因此,当您启动您的组件时,在 onCreate
您将收到最新的项目值,只要它已设置。它不需要被改变。您将在整个组件中拥有相同的值,如果实时数据发生变化,您的 myItem
也会更新。
您可以使用getSelected().getValue()
我是 android 中的 mvvm 架构新手。我正在将数据从 Fragment A 传递到 B 。我想将该数据存储在 Frag B 的视图模型中,并根据需要使用。据我了解,我需要在视图模型中定义两个这样的方法
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
并像
一样在片段中观察它model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
这很好,因为最初是在 oncreate 中调用 setitem 并且我正在获取数据。但是如果我在不同的时间因为几个不同的原因在片段中重复需要这个Item数据,并且这个数据不会改变,那么如何使用方法
getSelected()
因为我只使用了一次观察器,并且需要调用一些事件,如 getdata 或 post data 才能触发事件。那么如何实现呢。
我是否需要通过另一种方法多次调用 getvalue() 方法?我不确定这是否是正确的方法。请说明。
谢谢:)
.observe
方法不仅会观察一次,每次livedata值改变都会触发。据我所知,调用 .getValue()
获取实时数据的值没有任何问题,但由于您已经设置了一个观察者,您可以在那里更新您的 类' 项目变量:
class MyClass{
val myItem: Item
并在 onCreate 中:
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
myItem = item
});
编辑:要回答您的评论,您可以使用 .getValue()
,没有任何问题。根据 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.
因此,当您启动您的组件时,在 onCreate
您将收到最新的项目值,只要它已设置。它不需要被改变。您将在整个组件中拥有相同的值,如果实时数据发生变化,您的 myItem
也会更新。
您可以使用getSelected().getValue()