Android的ViewModel精确使用姿势?

程序员 2024-9-18 06:27:27 60 0 来自 中国
看了网上许多对于ViewModel的讲授,对比了官方的使用,自觉有点官方译文科普的意思,纵然看许多,仍旧没有醍醐灌顶的感觉,于是,深入源码分析后,便想将对于ViewModel的使用以及定位做一些简单的记录,如与编者有不一样的见解,渴望在评论区一起讨论。文章旨在抛砖引玉,并无讲授之意。
对于ViewModel的官方先容:

ViewModel 类旨在以注意生命周期的方式存储和管理界面干系的数据。ViewModel类让数据可在发生屏幕旋转等设置更改后继续留存。
1.gif 从先容来看,仿佛ViewModel有本身的生命周期?看到有些文章也是如许形貌,提到:ViewModel会维护本身的生命周期。那么,它真的会维护本身的生命周期吗?
题目一:ViewModel生命周期?

起首,ViewModel是怎样创建的?
class MainViewModel : ViewModel() {}class MainActivity : ComponentActivity() { private val model: MainViewModel by viewModels()}我通过官方给的委托函数举行了ViewModel的初始化,直接跟进去检察ViewModel的创建,可以找到关键的创建语句,
ViewModelProvider(store, factory).get(MainViewModel::class.java)直接跟到get方珐的实现
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {        String canonicalName = modelClass.getCanonicalName();        ……略过        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);    } 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 {            if (viewModel != null) {            }        }        if (mFactory instanceof KeyedFactory) {            //走到这里,记着create方法            viewModel = ((KeyedFactory) mFactory).create(key, modelClass);        } else {            viewModel = mFactory.create(modelClass);        }        //请记着这个东西        mViewModelStore.put(key, viewModel);        return (T) viewModel;    }那么可以看出来ViewModelProvider的两个参数

  • mViewModelStore :ViewModel的复用有关
  • Factory :与创建有关
先不管复用规则,找到当前创建ViewModel的Factory,找到委托方法的factory可以看到
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(    noinline factoryProducer: (() -> Factory)? = null): Lazy<VM> {     val factoryPromise = factoryProducer ?: {        defaultViewModelProviderFactory     }     return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)}找到ComponentActivity的默认Factory->SavedStateViewModelFactory
    @NonNull    @Override    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {        if (mDefaultFactory == null) {            mDefaultFactory = new SavedStateViewModelFactory(                    getApplication(),                    this,                    getIntent() != null ? getIntent().getExtras() : null);        }        return mDefaultFactory;    }    //趁便看一下它的构造方法    public SavedStateViewModelFactory(@Nullable Application application,            @NonNull SavedStateRegistryOwner owner,            @Nullable Bundle defaultArgs) {        mSavedStateRegistry = owner.getSavedStateRegistry();        mLifecycle = owner.getLifecycle();        mDefaultArgs = defaultArgs;        mApplication = application;        //这里很关键        mFactory = application != null                ? ViewModelProvider.AndroidViewModelFactory.getInstance(application)                : ViewModelProvider.NewInstanceFactory.getInstance();    }可以看到,在创建SavedStateViewModelFactory的同时,又看到了两个Factory。
暂且不管,追一下这个默认的Factory是怎样实行Create方法的
public <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass) {        boolean isAndroidViewModel = AndroidViewModel.class.isAssignableFrom(modelClass);        Constructor<T> constructor;        if (isAndroidViewModel && mApplication != null) {            constructor = findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE);        } else {            constructor = findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE);        }        //这句解释很故意思,留意。        // doesn't need SavedStateHandle          if (constructor == null) {            return mFactory.create(modelClass);        }        SavedStateHandleController controller = SavedStateHandleController.create(                mSavedStateRegistry, mLifecycle, key, mDefaultArgs);        try {            T viewmodel;            if (isAndroidViewModel && mApplication != null) {                viewmodel = constructor.newInstance(mApplication, controller.getHandle());            } else {                viewmodel = constructor.newInstance(controller.getHandle());            }            return viewmodel;    }这段代码是在探求ViewModel的构造器,可以看到这段代码的末了是要调用ViewModel的两个带参构造函数。
这里是个疑点,为什么要通报参数呢?为什么会固定有一个参数?
先保存疑问,继续看可以发现,我创建的ViewModel走了在SavedStateViewModelFactory构造函数中创建的Factory,这里发现AndroidViewModelFactory派生自NewInstanceFactory,再看一下AndroidViewModelFactory的create函数是怎样实现的
  public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {            if (AndroidViewModel.class.isAssignableFrom(modelClass)) {                return modelClass.getConstructor(Application.class).newInstance(mApplication);            }            return super.create(modelClass);        }    }发现AndroidViewModelFactory会判断AndroidViewModel是不是modelClass超类或超接口,假如是,则直接调用构造函数的Application参数方法,
假如不是
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {      return modelClass.newInstance();        }直接创建。
那么ViewModel就创建完毕了,emm...等等,我不是要找它的生命周期吗?为什么没有看到有关生命周期的代码?
难道奥秘都在刚才忘记的mViewModelStore中?看一下它的代码
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());    }    public final void clear() {        for (ViewModel vm : mMap.values()) {            vm.clear();        }        mMap.clear();    }}这。。。不就是个容器吗?它在哪里创建的?再回顾一下委托函数
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(    noinline factoryProducer: (() -> Factory)? = null): Lazy<VM> {    val factoryPromise = factoryProducer ?: {        defaultViewModelProviderFactory    }    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)}哦,可以看到在我注册的Activity中有一个viewModelStore,那么它是怎样创建的?
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.");        }        ensureViewModelStore();        return mViewModelStore;    }    void ensureViewModelStore() {        if (mViewModelStore == null) {            NonConfigurationInstances nc =                    (NonConfigurationInstances) getLastNonConfigurationInstance();            if (nc != null) {                mViewModelStore = nc.viewModelStore;            }            if (mViewModelStore == null) {                mViewModelStore = new ViewModelStore();            }        }    }这里的getLastNonConfigurationInstance()只须要知道,这个是一种界面规复与生存的API,跟它一样的有我们熟知的onSaveInstanceState / onRestoreInstanceState,假如你感爱好可以查阅资料,不外这个Api在新的Sdk中已经不发起使用了,这里一会我们继续谈。
以是说,ViewModelStore生存了每个ViewModel的实例,在页面重构时做了处理处罚。让每个界面的ViewModelStore不会因为重构而消散。那么,它怎样才气消散呢?难道ViewModel会不绝存在吗?
固然不是,ViewModelStore显着有clear()方法,那么它的调用机遇是怎样的呢?


查找了下,第一个正是我当前想要知道的,它对应的代码如下
public ComponentActivity() {        getLifecycle().addObserver(new LifecycleEventObserver() {            @Override            public void onStateChanged(@NonNull LifecycleOwner source,                    @NonNull Lifecycle.Event event) {                if (event == Lifecycle.Event.ON_DESTROY) {                    mContextAwareHelper.clearAvailableContext();                    if (!isChangingConfigurations()) {                        getViewModelStore().clear();                    }                }            }        });}以是,在创建ComponentActivity的时间注册了监听当生命周期到ON_DESTORY的时间而且不是更改设置,就清空Store。
分析完毕。
结论:ViewModel并没有本身的生命周期,官方所谓的能在界面变动时不丢失数据,也是因为ViewModel的容器在对应的逻辑做了生存处理处罚。
4.gif 题目二:既然云云,那么我可不可以制作一个由我控制生命周期的ViewModel呢?

固然可以
class AppViewModelStore : ViewModelStoreOwner , LifecycleEventObserver{        var store: ViewModelStore = ViewModelStore()    override fun getViewModelStore(): ViewModelStore {        return store    }    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {        //在Life走到ON_PAUSE清算。举例阐明,不发起使用。        if (event == Lifecycle.Event.ON_PAUSE) {            store.clear()        }    }}//使用ViewModelProvider(AppViewModelStore()).get(MainViewModel::class.java) 5.gif 题目三:我可不可以创建一个自界说参数的ViewModel呢?

分析源码可以知道,store负责ViewModel生存与烧毁,Factory负责创建,以是直接重写Factory即可。
class MyVMFactory : ViewModelProvider.Factory {    override fun <T : ViewModel?> create(modelClass: Class<T>): T {        return MainViewModel(参数) as T    }}//使用ViewModelProvider(AppViewModelStore(),MyVMFactory()).get(MainViewModel::class.java)只须要像源码那样创建就可以,只要把握ViewModelStore的生存与烧毁即可。

到这里,不免有点失落,viewModel就这?
google真的只是帮开发者做了这些吗?就当我准备竣事的时间,突然想起,在分析ViewModel生命周期中的一段解释
    /**     * Use this instead of {#onRetainNonConfigurationInstance()}.     * Retrieve later with {#getLastCustomNonConfigurationInstance()}.     *     * @deprecated Use a { androidx.lifecycle.ViewModel} to store non config state.     */是的,在getLastCustomNonConfigurationInstance()方法与onRetainNonConfigurationInstance()方法上的解释,让我用ViewModel去做设置项的东西,相称于,onSaveInstanceState与onRestoreInstanceState,可以用ViewModel直接设置。
看到这句话你明确了吗?
我举一个开发中的例子:
当用户的手机在背景很久之后,体系会采取应用的资源,导致一些数据丢失,打开应用会丢失数据大概瓦解,因此许多的开发者会把一部门数据做当地长期化处理处罚,没有长期化处理处罚的数据须要用onSaveInstanceState与onRestoreInstanceState举行生存与规复。然后项目的代码变成了如许
  override fun onSaveInstanceState(outState: Bundle) {        outState.putBoolean("MBoolean", true)        outState.putInt("MInt", 1)        outState.putString("MString", "save Info")        ```        省略        ```        super.onSaveInstanceState(outState)    }    override fun onRestoreInstanceState(savedInstanceState: Bundle) {        savedInstanceState.getBoolean("MBoolean", true)        savedInstanceState.getInt("MInt", 1)        savedInstanceState.getString("MString", "save Info")        ```        省略        ```        super.onRestoreInstanceState(savedInstanceState)    }是的,如许不轻易维护,大量的代码让人摸不着头脑,因此许多应用都同一让用户重新加载。
那么用ViewModel怎么办理了这个题目呢?
class MainViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {    fun getType(){        ```        业务逻辑        ```        savedStateHandle.get<String>("sKey")    }    fun putMessage(){        ```        业务逻辑        ```        savedStateHandle["sKey"] = "save info"    }}只须要在ViewModel的构造器中添加SavedStateHandle参数即可。
它的创建是在我的第一个迷惑点,在分析Factory的创建代码中对于构造器的选择。
当一次业务代码完成后即可选择是否要将业务内容生存下来,当体系因内存不敷采取应用数据后,应用仍旧能第一时间回到当前界面。对于开发者来说,只须要选择生存与回调的数据。
详细代码请参考
SavedStateViewModelFactory.java public <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass) {     ……省略    SavedStateHandleController controller = SavedStateHandleController.create(                mSavedStateRegistry, mLifecycle, key, mDefaultArgs);    ……}因篇幅题目,不做详细分析。
实在这些东西就是在开发者文档中的一些用法,只是我从一个点走过了全程,在我没有阅读文档环境下,我发现了这些用法,于是便去文档中举行查找。地点在这里
末了

我突然想到,假如如许那ViewModel的构造函数岂不是无法自界说了?而且自界说ViewModelStore也不能用了?
但是,反过来想想,Google也没有说ViewModel支持这些做法,而且,我的一些想法显着是在粉碎ViewModel自身的计划。难怪Google由最初的教各人自界说Factory通报参数到只字不提。
结论


  • ViewModel生命周期?
    ViewModel本身没有生命周期,装载ViewModel的容器ViewModelStore有生命周期。
  • 我可不可以制作一个由我控制生命周期的ViewModel呢?
    可以,但是创建了之后将失去ViewModel的意义。
  • 我可不可以创建一个自界说参数的ViewModel呢?
    可以,但是创建了之后将失去ViewModel的长处。
  • ViewModel到底是什么?
    精确使用它是有生命的容器
    错误使用它是数据容器。
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 22:31, Processed in 0.206764 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表