美文网首页
jetpack 理解SavedStateHandle

jetpack 理解SavedStateHandle

作者: 雨之都 | 来源:发表于2023-08-02 15:11 被阅读0次

    jetpack库 理解SavedStateHandle

    作用

    和ViewModel协作,用于从Activity销毁重建中恢复ViewModel的相关状态数据,我们知道当Activity被安卓系统销毁和重建的时候会调用onSaveInstanceState和onRestoreInstanceState方法,这个方法对于ViewModel来说是无法感知的,SavedStateHandle填补了这一空白,使得ViewModel可以通过此来保存一些状态数据

    描述

    SavedStateHandle是一个key-value映射,用于通过set()和get()方法向已保存的状态中检索和写入数据

    如何使用?

    1. 将SavedStateHandle作为ViewModel的构造参数
    2. ViewModel内部通过SavedStateHandle.getLiveData方法来生成一个 LiveData 对象,LiveData中的数据就是我们想要持久化保存的数据,如果Activity重建,这个LiveData中就会是重建的数据

    支持的类型

    理论上来说Bundle可保存的类型都支持

    原理分析

    • SavedStateRegistryOwner

    用来表示这个类拥有数据重建的能力,用来提供SavedStateRegistry

    • SavedStateRegistryController

    SavedStateRegistry的控制类

    • SavedStateRegistry

    数据存储和恢复

    • SavedStateProvider

    将要保存的数据通过Bundle封装起来

    基本关系

    SavedStateRegistryOwner → SavedStateRegistryController → SavedStateRegistry → SavedStateProvider

    SavedStateRegistryController可以理解成是SavedStateRegistry的包装类

    代码流程分析

    保存数据

    1.png

    在Activity调用onSaveInstanceState的时候,调用了SavedStateRegistryController的performSave方法,该方法如下

    @MainThread
        fun performSave(outBundle: Bundle) {
            savedStateRegistry.performSave(outBundle)
        }
    
    

    直接调用了SavedStateRegistry的performSave方法

        @MainThread
        @Suppress("INACCESSIBLE_TYPE")
        fun performSave(outBundle: Bundle) {
            val components = Bundle() // 创建一个Bundle
                    // 上一次重建保留的状态先保留
            if (restoredState != null) {
                components.putAll(restoredState)
            }
            val it: Iterator<Map.Entry<String, SavedStateProvider>> =
                this.components.iteratorWithAdditions()
            // 可以看到,这里基本上是遍历components,然后调用saveState方法,放到我们创建的bundle中
            while (it.hasNext()) {
                val (key, value) = it.next()
                components.putBundle(key, value.saveState())
            }
                    // 最后将这部分数据保存到outBundle中
            if (!components.isEmpty) {
                outBundle.putBundle(SAVED_COMPONENTS_KEY, components)
            }
        }
    
    

    重建数据

    重建数据是在onCreate中重建的

    @OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            // Restore the Saved State first so that it is available to
            // OnContextAvailableListener instances
            mSavedStateRegistryController.performRestore(savedInstanceState);
            mContextAwareHelper.dispatchOnContextAvailable(this);
            super.onCreate(savedInstanceState);
            ReportFragment.injectIfNeededIn(this);
            if (BuildCompat.isAtLeastT()) {
                mOnBackPressedDispatcher.setOnBackInvokedDispatcher(
                        Api33Impl.getOnBackInvokedDispatcher(this)
                );
            }
            if (mContentLayoutId != 0) {
                setContentView(mContentLayoutId);
            }
        }
    
    

    调用了Controller的performRestore方法

    @MainThread
        fun performRestore(savedState: Bundle?) {
            // To support backward compatibility with libraries that do not explicitly
            // call performAttach(), we make sure that work is done here
            if (!attached) {
                performAttach()
            }
            val lifecycle = owner.lifecycle
            check(!lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                ("performRestore cannot be called when owner is ${lifecycle.currentState}")
            }
            savedStateRegistry.performRestore(savedState)
        }
    
    

    最终调用了SavedStateRegistry的performRestore方法

    internal fun performRestore(savedState: Bundle?) {
            check(attached) {
                ("You must call performAttach() before calling " +
                    "performRestore(Bundle).")
            }
            check(!isRestored) { "SavedStateRegistry was already restored." }
            restoredState = savedState?.getBundle(SAVED_COMPONENTS_KEY)
    
            isRestored = true
        }
    
    

    将之前保存的值序列化到restoredState中

    上诉SavedStateRegistry机制实现了对于数据的保存,需要使用这一套机制需要实现SavedStateProvider,然后通过SavedRegistry的registerSavedStateProvider将自己注册到里面去就可以了

    那么这套机制是如何被ViewModel使用的呢,Activity和Fragment实现了HasDefaultViewModelProviderFactory接口,如Activity

    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
            if (mDefaultFactory == null) {
                mDefaultFactory = new SavedStateViewModelFactory(
                        getApplication(),
                        this,
                        getIntent() != null ? getIntent().getExtras() : null);
            }
            return mDefaultFactory;
        }
    
    

    在SavedStateViewModelFactory创建ViewModel中的时候,如果ViewModel的构造函数中有SavedStateHandle,通过

    LegacySavedStateHandleController.create(
                savedStateRegistry!!, lifecycle, key, defaultArgs
            )
    
    

    创建SavedStateHandleController进而获取SavedStateHandle.

    fun create(
            registry: SavedStateRegistry,
            lifecycle: Lifecycle,
            key: String?,
            defaultArgs: Bundle?
        ): SavedStateHandleController {
                    // 从registry获取和这个ViewModel有关的bundle
            val restoredState = registry.consumeRestoredStateForKey(key!!)
                    // 这个方法是吧restoreState中保存的key和value拆分出来,保存成map   
            val handle = createHandle(restoredState, defaultArgs)
            val controller = SavedStateHandleController(key, handle)
            controller.attachToLifecycle(registry, lifecycle)
            tryToAddRecreator(registry, lifecycle)
            return controller
        }
    
    

    最后创建ViewModel成功,此时SavedHandle也有了保存的数据了,SavedStateHandleController创建之后,会把创建的SavedStateProvider注册到StateRegistry中去,实现了数据的保存

    相关文章

      网友评论

          本文标题:jetpack 理解SavedStateHandle

          本文链接:https://www.haomeiwen.com/subject/talppdtx.html