Android开发JetPack之ViewModel

释放双眼,带上耳机,听听看~!
我们认识中的ViewModel是什么

Viewmodel其实就是activity中一个普通的实体。Activity持有viewmodel的引用,业务逻辑在viewmodel进行,关于界面和ui的操作在activity中进行,而添加和释放资源和viewmodel有关的那么就在viewmodel中设置函数,然后在activity中调用。ViewModel作为Activity/Fragment与其他组件的连接器,负责转换和聚合Model中返回的数据,使这些数据易于显示,并把这些数据改变及时的通知给Activity/Fragment。

ViewModel的生命周期

从图中看出,Activity的生命周期不断变化,经历了被销毁重新创建,而ViewModel的生命周期没有发生变化。

从创建一个viewModel入手分析源码:
MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

进入ViewModelProviders.of(this)方法:

 
    
    public static ViewModelProvider of( FragmentActivity activity) {
        return of(activity, null);
    }

    
    
    public static ViewModelProvider of( Fragment fragment,  Factory factory) {
        Application application = checkApplication(checkActivity(fragment));
        if (factory == null) {
            factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
        return new ViewModelProvider(fragment.getViewModelStore(), factory);
    }

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

checkApplication(activity)会获取该activity所属的application。
ViewModelProvider.AndroidViewModelFactory.getInstance(application)会创建一个单例的AndroidViewModelFactory,并从activity或fragment中获取viewmodelstore,作为两个个参数传入ViewModelProvider构造方法,最后会新建一个ViewModelProvider作为返回。

ViewModelStore代码实现如下:

public class ViewModelStore {

    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.put(key, viewModel);
        if (oldViewModel != null) {
            oldViewModel.onCleared();
        }
    }

    final ViewModel get(String key) {
        return mMap.get(key);
    }

    Set<String> keys() {
        return new HashSet<>(mMap.keySet());
    }

    /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        mMap.clear();
    }
}

从ViewModelStore的源码可以看出,ViewModel实际上是以HashMap<String,ViewModel>的形式被缓存起来了。ViewModel与页面之间没有直接的关联,它们通过ViewModelProvider进行关联。当页面需要ViewModel时,会向ViewModelProvider索要,ViewModelProvider检查该ViewModel是否已经存在于缓存中,若存在,则直接返回,若不存在,则实例化一个。因此,Activity由于配置变化导致的销毁重建并不会影响ViewModel,ViewModel是独立于页面而存在的。也正因为此,我们在使用ViewModel时,需要特别注意,不要向ViewModel中传入任何类型的Context或带有Context引用的对象,这可能会导致页面无法被销毁,从而引发内存泄漏。

AndroidViewModelFactory类代码如下:

 public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {

        private static AndroidViewModelFactory sInstance;

        /**
         * Retrieve a singleton instance of AndroidViewModelFactory.
         *
         * @param application an application to pass in {@link AndroidViewModel}
         * @return A valid {@link AndroidViewModelFactory}
         */
        @NonNull
        public static AndroidViewModelFactory getInstance(@NonNull Application application) {
            if (sInstance == null) {
                sInstance = new AndroidViewModelFactory(application);
            }
            return sInstance;
        }

        private Application mApplication;

        /**
         * Creates a {@code AndroidViewModelFactory}
         *
         * @param application an application to pass in {@link AndroidViewModel}
         */
        public AndroidViewModelFactory(@NonNull Application application) {
            mApplication = application;
        }

        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
                //noinspection TryWithIdenticalCatches
                try {
                    return modelClass.getConstructor(Application.class).newInstance(mApplication);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                } catch (InstantiationException e) {
                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                }
            }
            return super.create(modelClass);
        }
    }

ViewModel是抽象类,AndroidViewModel继承于ViewModel,AndroidViewModelFactory从它的create方法可以看出,通过反射生成ViewModel的实现类。

get(MyViewModel.class)部分

进入到了ViewModelProvider进行执行,ViewModelProvider代码如下:

public class ViewModelProvider {

    private static final String DEFAULT_KEY =
            "androidx.lifecycle.ViewModelProvider.DefaultKey";

        public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
        mFactory = factory;
        mViewModelStore = store;
    }

    @NonNull
    @MainThread
    public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
        String canonicalName = modelClass.getCanonicalName();    //注释1
        if (canonicalName == null) {
            throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
        }
        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);  //注释2
    }

    @NonNull
    @MainThread
    public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
        ViewModel viewModel = mViewModelStore.get(key);  

        if (modelClass.isInstance(viewModel)) {
            //noinspection unchecked
            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);
        //noinspection unchecked
        return (T) viewModel;
    }
}

过程分析:注释1处得到类的名称,对这个名称进行字符串拼接,拼接上前缀androidx.lifecycle.ViewModelProvider.DefaultKey,作为注释2处方法的参数,作为key值去ViewModelStore中获取viewmodel实例。如果ViewModel能转换为modelClass类的对象,直接返回该ViewModel。否则就会通过AndroidViewModelFactory的create方法通过反射创建一个ViewModel,并将其存储到ViewModelStore中。

AndroidViewModel与ViewModel类:
public class AndroidViewModel extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private Application mApplication;

    public AndroidViewModel(@NonNull Application application) {
        mApplication = application;
    }

    /**
     * Return the application.
     */
    @SuppressWarnings("TypeParameterUnusedInFormals")
    @NonNull
    public <T extends Application> T getApplication() {
        //noinspection unchecked
        return (T) mApplication;
    }
}

在使用ViewModel时,不能将任何类型的Context或含有Context引用的对象传入ViewModel,因为这可能会导致内存泄漏。但如果你希望在ViewModel中使用Context,该怎么办呢?可以让你的viewmodel继承AndroidViewModel类,它继承自ViewModel,并接收Application作为Context。这意味着,它的生命周期和Application是一样的,那么这就不算是一个内存泄漏了。

人已赞赏
Android文章

Android MVVM开发模式解读

2021-1-30 1:22:23

Android文章

Android开发JetPack之LiveData源码解析

2021-1-30 2:37:58

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索