ViewModel is a class that is responsible for preparing and managing the data for an
[Activity]
or a[Fragment]
.
ViewModel 是一个类,负责准备和管理活动或片段的数据。它还处理 Activity/Fragment 与应用程序其余部分的通信(例如调用业务逻辑类)。
A ViewModel is always created in association with a scope (a fragment or an activity) and will be retained as long as the scope is alive. E.g. if it is an Activity, until it is finished.
ViewModel 总是与作用域(片段或活动)关联创建,并且只要作用域是活的,它就会保留。例如,如果它是一个活动,直到它完成。
In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel.
换句话说,这意味着如果一个 ViewModel 的所有者因为一个配置变更而被销毁(例如旋转) ,那么 ViewModel 就不会被销毁。所有者的新实例将重新连接到现有的 ViewModel。
The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment. The Activity or the Fragment should be able to observe changes in the ViewModel. ViewModels usually expose this information via
[LiveData]
or Android Data Binding. You can also use any observability construct from you favorite framework.
ViewModel 的目的是获取和保存活动或片段所需的信息。活动或片段应该能够观察 ViewModel 中的变化。通常通过 LiveData 或 Android Data Binding 公开这些信息。您还可以使用您喜欢的框架中的任何可观察性构造。
ViewModel's only responsibility is to manage the data for the UI. It should never access your view hierarchy or hold a reference back to the Activity or the Fragment.
ViewModel 的唯一职责是管理 UI 的数据。它永远不应该访问您的视图层次结构或保存对活动或片段的引用。
Typical usage from an Activity standpoint would be:
从活动的角度来看,典型的用法是:
public class UserActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_layout);
final UserModel viewModel = new ViewModelProvider(this).get(UserModel.class);
viewModel.getUser().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User data) {
// update ui.
}
});
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.doAction();
}
});
}
}
ViewModel would be:
模型应该是:
public class UserModel extends ViewModel {
private final MutableLiveData<User> userLiveData = new MutableLiveData<>();
public LiveData<User> getUser() {
return userLiveData;
}
public UserModel() {
// trigger user load.
}
void doAction() {
// depending on the action, do necessary business logic calls and update the
// userLiveData.
}
}
ViewModels can also be used as a communication layer between different Fragments of an Activity. Each Fragment can acquire the ViewModel using the same key via their Activity. This allows communication between Fragments in a de-coupled fashion such that they never need to talk to the other Fragment directly.
ViewModels 还可以用作活动的不同片段之间的通信层。每个片段可以通过它们的 Activity 使用相同的键获得 ViewModel。这允许片段之间以解耦合的方式进行通信,这样它们就不需要直接与其他片段通信。
网友评论