天天看點

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 的引用。

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    }      
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    }