【发布时间】:2020-05-14 15:49:58
【问题描述】:
我正在阅读有关 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 概览在 Activity 中实现了观察,而 ViewModel 概览在片段中。这可能是为什么要在 2 步 vs 1 步过程中实施观察的原因吗?
一个比另一个更好吗?还是它们是等效的编写方式?
【问题讨论】:
标签: java android android-fragments android-livedata android-viewmodel