Jetpack:ViewModel

1.引入背景

引入ViewModel之前,存在如下几个问题:
(1)有的时候一个Activity里面嵌套了多个fragment,但是这些fragment里面用的是同一个数据,为了同步这些数据,我们需要用接口来传参,很麻烦
(2)屏幕旋转,会销毁重建,如果数据类型比较简单,同时数据量也不大,可以通过onSaveInstanceState()存储数据.但如果是大量数据,不方便序列化及反序列化,则上述方法将不适用.

2.ViewModel的使用

(1)gradle中引入

 implementation 'android.arch.lifecycle:extensions:1.1.1'

(2)新建ViewModel实体类

public class UserModel extends ViewModel {
    String name;
    int age;
}

(3)获取ViewModel

UserModel model = ViewModelProviders.of(this).get(UserModel.class);

3.源码解析

先看一下of函数

    public static ViewModelProvider of(@NonNull FragmentActivity activity,
            @Nullable Factory factory) {
        Application application = checkApplication(activity);
        if (factory == null) {
            factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
        return new ViewModelProvider(ViewModelStores.of(activity), factory);
    }

重点看这个ViewModelStores.of(activity)

    public static ViewModelStore of(@NonNull FragmentActivity activity) {
        if (activity instanceof ViewModelStoreOwner) {
            return ((ViewModelStoreOwner) activity).getViewModelStore();
        }
        return holderFragmentFor(activity).getViewModelStore();
    }
    public static ViewModelStore of(@NonNull Fragment fragment) {
        if (fragment instanceof ViewModelStoreOwner) {
            return ((ViewModelStoreOwner) fragment).getViewModelStore();
        }
        return holderFragmentFor(fragment).getViewModelStore();
    }

如果实现了ViewModelStoreOwner,就返回ViewModelStore,否则就新生成一个HolderFragment来获取ViewModelStore
那就进去看看HolderFragment如何实现ViewModelStore的(代码已简化)

public class HolderFragment extends Fragment implements ViewModelStoreOwner {

    private ViewModelStore mViewModelStore = new ViewModelStore();

    public HolderFragment() {
        setRetainInstance(true);//屏幕旋转不销毁重绘
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sHolderFragmentManager.holderFragmentCreated(this);//内部就是生成fragment
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewModelStore.clear();
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return mViewModelStore;
    }
}

ViewModelStore又是啥呢?点进去看就知道是HashMap

4.总结

ViewModel说白了就是内部生成一个fragment来管理生命周期,同时用HashMap保存数据,相对简单.它和LiveData以及Lifecycle组合使用会更好,接下来就会介绍LiveData

你可能感兴趣的:(Jetpack:ViewModel)