Android ——MVVM基本框架(ViewModel)
自己对MVVM的理论知识了解了许多,但是对于Android中究竟要如何体现,一直都不是很明了,今天在在官方API里,看到了一个经典的MVVM架构。
ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).
A ViewModel is always created in association with a scope (an 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.
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.
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'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 是一个类,负责为 Activity 或 Fragment 准备和管理数据。它还处理 Activity/Fragment 与应用程序其余部分的通信(例如调用业务逻辑类)。 ViewModel 始终与作用域(片段或活动)相关联地创建,并且只要作用域处于活动状态就会保留。例如。如果它是一个Activity,直到它完成。 换句话说,这意味着如果 ViewModel 的所有者因配置更改(例如旋转)而被销毁,则它不会被销毁。所有者的新实例将重新连接到现有的 ViewModel。 ViewModel 的目的是获取并保存 Activity 或 Fragment 所需的信息。 Activity 或 Fragment 应该能够观察到 ViewModel 中的变化。 ViewModel 通常通过 LiveData 或 Android 数据绑定公开这些信息。您还可以使用您喜欢的框架中的任何可观察性构造。 ViewModel 的唯一职责是管理 UI 的数据。它永远不应该访问您的视图层次结构或保留对 Activity 或 Fragment 的引用。
其中activity如下:
1 public class UserActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.user_activity_layout); 7 final UserModel viewModel = ViewModelProviders.of(this).get(UserModel.class); 8 viewModel.userLiveData.observer(this, new Observer () { 9 @Override 10 public void onChanged(@Nullable User data) { 11 // update ui. 12 } 13 }); 14 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { 15 @Override 16 public void onClick(View v) { 17 viewModel.doAction(); 18 } 19 }); 20 } 21 }
然后ViewModel如下:
1 public class UserModel extends ViewModel { 2 private final MutableLiveData<User> userLiveData = new MutableLiveData<>(); 3 4 public LiveData<User> getUser() { 5 return userLiveData; 6 } 7 8 public UserModel() { 9 // trigger user load. 10 } 11 12 void doAction() { 13 // depending on the action, do necessary business logic calls and update the 14 // userLiveData. 15 } 16 }