ViewModel源码简单分析

一、跟踪ViewModel的创建以及保存过程。
ViewModelProvider(this).get(MainViewModel::class.java)
ViewModel是通过ViewModelProvider创建的,ViewModelProvider里面只有两个成员。
    private final Factory mFactory;
    private final ViewModelStore mViewModelStore;
这两个成员分别负责创建ViewModel和保存ViewModel,具体代码在get函数里面,mFactory主要负责创建,mViewModelStore负责把创建好的ViewModel保存起来。
    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 StatementWithEmptyBody
            if (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;
    }

mViewModelStore这个成员变量就是由ViewModelProvider的构造函数传入的ViewModelStoreOwner里面取到的。
//构造函数把ViewModelStoreOwner传入,this就是实现了ViewModelStoreOwner接口的Acticity
ViewModelProvider(this)
//从ViewModelStoreOwner里面拿到ViewModelStore
owner.getViewModelStore()
而ViewModelStoreOwner这个接口是由 ComponentActivity实现的
ViewModelStoreOwner类
public interface ViewModelStoreOwner {
    /**
     * Returns owned {@link ViewModelStore}
     *
     * @return a {@code ViewModelStore}
     */
    @NonNull
    ViewModelStore getViewModelStore();
}

ComponentActivity中实现的getViewModelStore方法
@NonNull
@Override
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) {
        NonConfigurationInstances nc =
                (NonConfigurationInstances) getLastNonConfigurationInstance();
        if (nc != null) {
            // Restore the ViewModelStore from NonConfigurationInstances
            mViewModelStore = nc.viewModelStore;
        }
        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
    }
    return mViewModelStore;
}
ViewModelStore是通过getLastNonConfigurationInstance()获取到的
而储存流程是在 onRetainNonConfigurationInstance() 函数中执行的。
这两个函数是Activity中用于 当config 变化时, 保存 state的工具方法,也是因为如此,ViewModel 可以在Activity 由于Config的变化销毁重建时,仍然能用于保存数据。
二、Fragment中的ViewModel是咋回事
在Fragment中,创建ViewModel的流程和在Activity中是一样的
ViewModelProvider(this).get(MainFragmentViewModel::class.java)
所以可以知道,Fragment也实现了ViewModelStoreOwner接口。
@NonNull
@Override
public ViewModelStore getViewModelStore() {
    if (mFragmentManager == null) {
        throw new IllegalStateException("Can't access ViewModels from detached fragment");
    }
    return mFragmentManager.getViewModelStore(this);
    }
Fragment的ViewModelStore是通过FragmentManager拿到的,而在FragmentManager里面,其实又往下走了一层。
FragmentManager类
@NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
    return mNonConfig.getViewModelStore(f);
}
mNonConfig是一个ViewModel,FragmentManagerViewModel
private FragmentManagerViewModel mNonConfig;

/**
 * FragmentManagerViewModel is the always up to date view of the Fragment's
 * non configuration state
 * 这是一个专门用于用于管理Fragment的一些 状态 的 ViewModel
 */
final class FragmentManagerViewModel extends ViewModel {
@NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
    ViewModelStore viewModelStore = mViewModelStores.get(f.mWho);
    if (viewModelStore == null) {
        viewModelStore = new ViewModelStore();
        mViewModelStores.put(f.mWho, viewModelStore);
    }
    return viewModelStore;
}
FragmentManagerViewModel中维护了一个HashMap,每个Fragment的ViewModelStore都存在里面。
Fragment在Config变化时候的储存和还原部分,涉及到了Fragment的生命周期,跟FragmentManager 和 FragmentController 的部分源码我也还没有搞明白,所以就不做深入研究了。
总之,Fragment 的 ViewModel 全部是由 FragmentManager中的FragmentManagerViewModel来管理的来管理的。
三、总结
每个Activity和Fragment都有自己的一个ViewModelStore,里面可以储存多个ViewModel。
同一个Activity里面的所有Fragment 的ViewModelStore 都是由 FragmentManager里面的一个FragmentManagerViewModel 来管理的。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值