[我正在阅读与LiveData和ViewModels有关的Android文档,但遇到了使我感到困惑的条目。
在LiveData Overview示例代码像这样实现观察者
public class NameActivity extends AppCompatActivity {
private NameViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other code to setup the activity...
// Get the ViewModel.
model = new ViewModelProvider(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
nameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.getCurrentName().observe(this, nameObserver);
}}
创建更新UI的Observer<String>
和观察LiveData的.observe
的两步过程而在ViewModel Overview中,观察者的实现是
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
带有一个.observe
。我做了一些测试,看起来单个.observe
也能够更新UI。
我还注意到LiveData Overview在Activity中实现了观察,而ViewModel Overview在一个片段中。这是为什么观察是在2步对1步过程中实现的原因吗?
一个比另一个好吗?还是等同的书写方式?
两者之间几乎没有实际差异。这只是语法问题。
在第一个示例中,代码使用new Observer<String>()
创建实现Observer接口的对象的新实例。此实例传递到observe()
。
第二个示例实际上在做几乎完全相同的事情,除了它使用Java 8 lambda syntax折叠了许多用于定义Observer对象的代码,并简单地在调用observe()
的行内定义了新的Observer对象,甚至都没有命名。
无论您使用new Observer()
还是lambda语法,最终结果基本相同-创建并传递了一个新的Observer实例。