确保活动或片段具有可在其变为活动状态时立即显示的数据。
只要应用程序组件处于该STARTED状态,它就会从LiveData它正在观察的对象中接收最新值。只有LiveData在设置了要观察的对象时才会出现这种情况。
通常,LiveData仅在数据更改时才提供更新,并且仅在活动观察者时提供更新。
此行为的一个例外是观察者在从非活动状态更改为活动状态时也会收到更新。
此外,如果观察者第二次从非活动状态更改为活动状态,则只有在自上次活动状态以来该值发生更改时才会收到更新。
以下示例代码说明了如何开始观察LiveData对象:
public class NameActivity extends AppCompatActivity {
private NameViewModel mModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other code to setup the activity…
// Get the ViewModel.
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer nameObserver = new Observer() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
mNameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
}
}
observe()调用nameObserverafter作为参数传递后,onChanged()立即调用,提供存储的最新值mCurrentName。如果LiveData对象未设置值mCurrentName,onChanged()则不调用。
2.3更新LiveData对象
LiveData没有公开的方法来更新存储的数据。本MutableLiveData类公开setValue(T)和
postValue(T)方法公开,如果你需要编辑存储在一个值,你必须使用这些LiveData对象。
通常MutableLiveData用于ViewModel然后将ViewModel唯一的不可变LiveData对象暴露给观察者。
设置观察者关系后,您可以更新LiveData对象的值,如以下示例所示,当用户点击按钮时触发所有观察者:
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String another