本文主要是介绍Android JetPack ViewModel 源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
是什么?
ViewModel 用来存储页面相关的数据,当页面销毁的时候,存储数据也会清楚。但是当页面发生旋转的时候,并不会清楚数据。
怎么用?
UserViewModel userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
UserViewModel 是自己写的ViewModel,就可以拿到页面相关的ViewModel,在这个ViewModel 里我们可以获取LiveData,这样当异步数据加载完成的时候,我们可以更新Ui
public class UserViewModel extends ViewModel {private MutableLiveData<List<User>> users;public LiveData<List<User>> getUsers() {if (users == null) {users = new MutableLiveData<>(new ArrayList<>());}final List<User> value = users.getValue();Thread thread = Executors.defaultThreadFactory().newThread(new Runnable() {@Overridepublic void run() {UseDao useDao = UserDBManager.getInstance().getUseDao();List<User> usersAll = useDao.queryAll();if (value != null) {value.addAll(usersAll);}users.postValue(value);}});thread.start();return users;}}
如何实现的?
1.FragmentActivity 实现了 ViewModelStoreOwner 接口,在ComponentActivity 构造方法里面会监听OnDestory,如果不是页面状态改变,那么就会清楚ViewModelStore 里面的数据
androidx.activity.ComponentActivity#ComponentActivity()
getLifecycle().addObserver(new LifecycleEventObserver() {@Overridepublic void onStateChanged(@NonNull LifecycleOwner source,@NonNull Lifecycle.Event event) {if (event == Lifecycle.Event.ON_DESTROY) {if (!isChangingConfigurations()) {getViewModelStore().clear();}}}});
2.getViewModelStore 方法
public ViewModelStore getViewModelStore() {if (getApplication() == null) {throw new IllegalStateException("Your activity is not yet attached to the "+ "Application instance. You can't request ViewModel before onCreate call.");}if (mViewModelStore == null) {if (mViewModelStore == null) {mViewModelStore = new ViewModelStore();}}return mViewModelStore;}
判断当前Activity mViewModelStore 是不是空,如果是空就创建一个。
3.androidx.lifecycle.ViewModelProvider#get(java.lang.Class)
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {ViewModel viewModel = mViewModelStore.get(key);if (modelClass.isInstance(viewModel)) {if (mFactory instanceof OnRequeryFactory) {((OnRequeryFactory) mFactory).onRequery(viewModel);}return (T) viewModel;} else {//noinspection StatementWithEmptyBodyif (viewModel != null) {// TODO: log a warning.}}if (mFactory instanceof KeyedFactory) {viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);} else {viewModel = (mFactory).create(modelClass);}mViewModelStore.put(key, viewModel);return (T) viewModel;}
在这个方法里面会去调用工厂的create 创建ViewModel 对象,默认的实现为NewInstanceFactory:
总结:
ViewModel 最终的数据被存放在ViewModelStore 类 的成员变量Map 里,每一个Activity 都有自己的ViewModelStore. 当Activity 执行OnDestory 的时候,如果不是页面旋转,那么就会清空Map.
这篇关于Android JetPack ViewModel 源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!