ViewModel源码分析

1,005 阅读10分钟

官方介绍:ViewModel 类旨在以注重生命周期的方式存储和管理界面相关的数据。它有两个特点:

  • ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存
  • 跟Activity等组件生命周期绑定

使用

class ProfileViewModel : ViewModel(){
}

class ProfileActivity : FragmentActivity() {

    private lateinit var profileViewModel: ProfileViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
    }
    
    private fun initData() {
        profileViewModel = ViewModelProvider(this).get(ProfileViewModel::class.java)
    }

源码分析

基础功能分析

1. ViewModel类怎么做到让数据可在发生屏幕旋转等配置更改后继续留存

public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
    this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
            ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
            : NewInstanceFactory.getInstance());
}

它的构造函数接受一个ViewModelStoreOwner参数,查看可以发现ViewModelStoreOwner是一个接口,只定义了一个函数:

public interface ViewModelStoreOwner {
    /**
     * Returns owned {@link ViewModelStore}
     *
     * @return a {@code ViewModelStore}
     */
    @NonNull
    ViewModelStore getViewModelStore();
}

上边的例子,将this(FragmentActivity)作为参数传递进来。FragmentActivity继承于ComponentActivity,我们来看下它的源码,可以看到它实现了ViewModelStoreOwner接口。

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
}

我们再看回去上边ViewModelProvider的构造函数,调用了自己带有两个参数的构造函数,主要为mFactory和mViewModelStore做了赋值工作:

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

ComponentActivity除了实现ViewModelStoreOwner,还实现了HasDefaultViewModelProviderFactory接口,因此mFactory会使用它通过getDefaultViewModelProviderFactory()提供的值:

@NonNull
@Override
public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
    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 (mDefaultFactory == null) {
        mDefaultFactory = new SavedStateViewModelFactory(
                getApplication(),
                this,
                getIntent() != null ? getIntent().getExtras() : null);
    }
    return mDefaultFactory;
}

这里有个重要的类:SavedStateViewModelFactory,这里先不展开分析。继续看回去我们的使用例子,看下ViewModelProvider.get()函数:

@SuppressWarnings("unchecked")
@NonNull
@MainThread
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获取ViewModel,这里有两种情况:

  • 第一次获取时,mViewModelStore.get(key)获取到的viewModel肯定为空,继续往下执行,mFactory被赋值为SavedStateViewModelFactory。而SavedStateViewModelFactory是继承于ViewModelProvider.KeyedFactory,因此会走到viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);。这里通过指定的Factory来创建ViewModel对象。这块先放一放,接下来的环节和SavedStateViewModelFactory一起分析。
  • 假如mViewModelStore.get(key)获取到的viewModel不为空,则直接返回。假如要做到配置更改后数据继续留存,必须得保证mViewModelStore是一致的!而mViewModelStore是通过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;
}

假如为空的话,先通过getLastNonConfigurationInstance()获取:

Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial onCreate and onStart calls to the new instance, allowing you to extract any useful dynamic state from the previous instance.
Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its previous state (through the normal onSaveInstanceState(Bundle) mechanism) even if this function returns null.
Note: For most cases you should use the Fragment API Fragment.setRetainInstance(boolean) instead; this is also available on older platforms through the Android support libraries.
Returns:
the object previously returned by onRetainNonConfigurationInstance()

@Nullable
public Object getLastNonConfigurationInstance() {
    return mLastNonConfigurationInstances != null
            ? mLastNonConfigurationInstances.activity : null;
}

Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, including the activity instance itself, which can later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance. If you are targeting Build.VERSION_CODES.HONEYCOMB or later, consider instead using a Fragment with Fragment.setRetainInstance(boolean.
This function is called purely as an optimization, and you must not rely on it being called. When it is called, a number of guarantees will be made to help optimize configuration switching:
The function will be called between onStop and onDestroy.
A new instance of the activity will always be immediately created after this one's onDestroy() is called. In particular, no messages will be dispatched during this time (when the returned object does not have an activity to be associated with).
The object you return here will always be available from the getLastNonConfigurationInstance() method of the following activity instance as described there.

public Object onRetainNonConfigurationInstance() {
        return null;
}

这里有两个关键函数,我们看下api的说明:

  • onRetainNonConfigurationInstance:当由于配置发生变化导致的activity销毁时,系统会自动调用该函数。可以用于保存activity被重启时我们希望恢复的数据信息。
  • getLastNonConfigurationInstance:用于获取我们在onRetainNonConfigurationInstance保存的数据信息

onRetainNonConfigurationInstance定义在Activity,我们看下这个函数在ComponentActivity中的重写:

@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
    Object custom = onRetainCustomNonConfigurationInstance();

    ViewModelStore viewModelStore = mViewModelStore;
    if (viewModelStore == null) {
        // No one called getViewModelStore(), so see if there was an existing
        // ViewModelStore from our last NonConfigurationInstance
        NonConfigurationInstances nc =
                (NonConfigurationInstances) getLastNonConfigurationInstance();
        if (nc != null) {
            viewModelStore = nc.viewModelStore;
        }
    }

    if (viewModelStore == null && custom == null) {
        return null;
    }

    NonConfigurationInstances nci = new NonConfigurationInstances();
    nci.custom = custom;
    nci.viewModelStore = viewModelStore;
    return nci;
}

可以看到,在这里将整个mViewModelStore包装成NonConfigurationInstances,然后返回。这里也可以解析特点一:ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存。

2. 跟组件生命周期的绑定

它又是怎么跟组件的生命周期绑定的呢?我们接着分析,这里需要区分Activity和Fragment

  • Activity

直接看代码:

public ComponentActivity() {
    getLifecycle().addObserver(new LifecycleEventObserver() {
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                if (!isChangingConfigurations()) {
                    getViewModelStore().clear();
                }
            }
        }
    });
}

直接通过LifecycleEventObserver,当Lifecycle.Event.ON_DESTROY时,调用getViewModelStore().clear();。这里还判断了isChangingConfigurations,因为当配置导致的activity等重启时,是需要恢复ViewProvider提供的数据的,因此不能clear。

  • Fragment
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner {
    
    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        if (mFragmentManager == null) {
            throw new IllegalStateException("Can't access ViewModels from detached fragment");
        }
        return mFragmentManager.getViewModelStore(this);
    }        
    
    @NonNull
    @Override
    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
        if (mFragmentManager == null) {
            throw new IllegalStateException("Can't access ViewModels from detached fragment");
        }
        if (mDefaultFactory == null) {
            mDefaultFactory = new SavedStateViewModelFactory(
                    requireActivity().getApplication(),
                    this,
                    getArguments());
        }
        return mDefaultFactory;
    }    
}

Fragment同样继承了ViewModelStoreOwner和HasDefaultViewModelProviderFactory两个接口,可以看到它的getViewModelStore是调用了mFragmentManager.getViewModelStore(this),我们继续往里边看:

// FragmentManager.java
@NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
    return mNonConfig.getViewModelStore(f);
}

// FragmentManagerViewModel.java
@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.getViewModelStore()。FragmentManagerViewModel继承于ViewModel,它里边主要定义了Fragment和ViewModel之间的交互。继续查看,可以发现它定义了一个函数:void clearNonConfigState(@NonNull Fragment f):

void clearNonConfigState(@NonNull Fragment f) {
    if (FragmentManager.isLoggingEnabled(Log.DEBUG)) {
        Log.d(TAG, "Clearing non-config state for " + f);
    }
    // Clear and remove the Fragment's child non config state
    FragmentManagerViewModel childNonConfig = mChildNonConfigs.get(f.mWho);
    if (childNonConfig != null) {
        childNonConfig.onCleared();
        mChildNonConfigs.remove(f.mWho);
    }
    // Clear and remove the Fragment's ViewModelStore
    ViewModelStore viewModelStore = mViewModelStores.get(f.mWho);
    if (viewModelStore != null) {
        viewModelStore.clear();
        mViewModelStores.remove(f.mWho);
    }
}

这里边就包含了ViewModel的清除以及和Fragment的解绑工作。那我们看下它到底在哪里被调用的,看能否找到与生命周期相关的代码:

  • FragmentStateManager.destory
  • FragmentManager.moveToState
  • FragmentActivity--FragmentController--FragmentManager 这里也涉及到Activity和Fragment生命周期绑定的知识,有时间可以自己去看。看下FragmentStateManager.destory:
void destroy(@NonNull FragmentHostCallback<?> host,
        @NonNull FragmentManagerViewModel nonConfig) {
    if (FragmentManager.isLoggingEnabled(Log.DEBUG)) {
        Log.d(TAG, "movefrom CREATED: " + mFragment);
    }
    boolean beingRemoved = mFragment.mRemoving && !mFragment.isInBackStack();
    boolean shouldDestroy = beingRemoved || nonConfig.shouldDestroy(mFragment);
    if (shouldDestroy) {
        boolean shouldClear;
        if (host instanceof ViewModelStoreOwner) {
            shouldClear = nonConfig.isCleared();
        } else if (host.getContext() instanceof Activity) {
            Activity activity = (Activity) host.getContext();
            shouldClear = !activity.isChangingConfigurations();
        } else {
            shouldClear = true;
        }
        if (beingRemoved || shouldClear) {
            nonConfig.clearNonConfigState(mFragment);
        }
        mFragment.performDestroy();
        mDispatcher.dispatchOnFragmentDestroyed(mFragment, false);
    } else {
        mFragment.mState = Fragment.ATTACHED;
    }
}

假如context为activity,会判断是否配置变化导致的destory,假如不是,则做ViewModel相关的清除工作。

拓展功能

在上边的章节,我们遗留了两块东西没有讲:SavedStateViewModelFactory和它的create函数。在这个环节,我们着重讲这个类的作用。

这里先举一个场景:由于系统资源限制等原因导致 Activity 被销毁后,能否做到当 Activity 重建时之前加载的数据以及用户状态都能够得到恢复呢?

其实通过ViewModel的扩展使用也是可以做到的,先来个demo:

// ExpandViewModel.java
class ExpandViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {

    companion object {
        private const val KEY_EXPAND = "key_expand"
    }

    val expandLiveData = savedStateHandle.getLiveData<String>(KEY_EXPAND)
}

// MainActivity.java
class MainActivity : AppCompatActivity() {

    private lateinit var expandViewModel: ExpandViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initData()
    }

    private fun initData() {
        expandViewModel = ViewModelProvider(this).get(ExpandViewModel::class.java)
        findViewById<Button>(R.id.bt_update).setOnClickListener {
            expandViewModel.expandLiveData.value = "expand live data"
        }
        Log.i("MainActivity", "savedStateViewModel: $expandViewModel")
        Log.i("MainActivity", "savedStateViewModel.name: ${expandViewModel.expandLiveData.value}")
    }
}
  • 通过点击更新expandLiveData的值
  • 需要开发者模式下,开启:不保留活动,用于模拟 Activity 由于系统内存不足被销毁的场景

这跟我们开篇的例子有什么区别?主要区别:

  • 自定义的ExpandViewModel构造方法增加了一个SavedStateHandle的入参
  • 数据的保存与获取通过SavedStateHandle操作

那它是怎么做到的呢?接下来就要深入分析SavedStateViewModelFactory.create:

@NonNull
@Override
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());
        }
        viewmodel.setTagIfAbsent(TAG_SAVED_STATE_HANDLE_CONTROLLER, controller);
        return viewmodel;
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Failed to access " + modelClass, e);
    } catch (InstantiationException e) {
        throw new RuntimeException("A " + modelClass + " cannot be instantiated.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("An exception happened in constructor of "
                + modelClass, e.getCause());
    }
}

这里有三个主要判断:

  • modelClass是否为AndroidViewModel的子类,如果是并且mApplication不为空,则执行:
private static final Class<?>[] ANDROID_VIEWMODEL_SIGNATURE = new Class[]{Application.class,
        SavedStateHandle.class};
        
constructor = findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE);
  • 否则则执行:
private static final Class<?>[] VIEWMODEL_SIGNATURE = new Class[]{SavedStateHandle.class};

constructor = findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE);
  • 假如以上都不符合,则执行:
// doesn't need SavedStateHandle
if (constructor == null) {
    return mFactory.create(modelClass);
}

总结下可以发现,主要分为两大类的处理:构造函数是否包含SavedStateHandle.class作为入参。在demo中,我们为ExpandViewModel增加了一个SavedStateHandle的入参,因此流程会执行往下执行:

SavedStateHandleController controller = SavedStateHandleController.create(
        mSavedStateRegistry, mLifecycle, key, mDefaultArgs);
        
// 

这里会遇到另外一个类:SavedStateHandleController,我们接着看它的create函数:

static SavedStateHandleController create(SavedStateRegistry registry, Lifecycle lifecycle,
        String key, Bundle defaultArgs) {
    Bundle restoredState = registry.consumeRestoredStateForKey(key);
    SavedStateHandle handle = SavedStateHandle.createHandle(restoredState, defaultArgs);
    SavedStateHandleController controller = new SavedStateHandleController(key, handle);
    controller.attachToLifecycle(registry, lifecycle);
    tryToAddRecreator(registry, lifecycle);
    return controller;
}

主要做了几个事情:

  • 通过registry.consumeRestoredStateForKey(key)获取之前保存的数据
  • 通过SavedStateHandle.createHandle(restoredState, defaultArgs)将之前的数据保存到SavedStateHandle的mRegular
  • 通过controller.attachToLifecycle(registry, lifecycle);SavedStateHandleSavedStateProvider注册给registry,这里有什么作用?后边分析
  • 创建SavedStateHandleController并返回

那数据是怎么被保存起来的?然后registry又是怎么拿到的?我们看下registry:

// SavedStateViewModelFactory.java
@SuppressLint("LambdaLast")
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();
}

// ComponentActivity.java
final SavedStateRegistryController mSavedStateRegistryController =
            SavedStateRegistryController.create(this);
@NonNull
@Override
public final SavedStateRegistry getSavedStateRegistry() {
    return mSavedStateRegistryController.getSavedStateRegistry();
}

// SavedStateRegistryController.java
private SavedStateRegistryController(SavedStateRegistryOwner owner) {
    mOwner = owner;
    mRegistry = new SavedStateRegistry();
}

/**
 * Returns controlled {@link SavedStateRegistry}
 */
@NonNull
public SavedStateRegistry getSavedStateRegistry() {
    return mRegistry;
}

通过层层查找,最终registry直接指向:SavedStateRegistry:

An interface for plugging components that consumes and contributes to the saved state.
This objects lifetime is bound to the lifecycle of owning component: when activity or fragment is recreated, new instance of the object is created as well.

@SuppressLint("RestrictedApi")
public final class SavedStateRegistry {
    /**
     * An interface for an owner of this @{code {@link SavedStateRegistry} to restore saved state.
     *
     */
    @SuppressWarnings("WeakerAccess")
    @MainThread
    void performRestore(@NonNull Lifecycle lifecycle, @Nullable Bundle savedState) {
        if (mRestored) {
            throw new IllegalStateException("SavedStateRegistry was already restored.");
        }
        if (savedState != null) {
            mRestoredState = savedState.getBundle(SAVED_COMPONENTS_KEY);
        }
    
        lifecycle.addObserver(new GenericLifecycleObserver() {
            @Override
            public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_START) {
                    mAllowingSavingState = true;
                } else if (event == Lifecycle.Event.ON_STOP) {
                    mAllowingSavingState = false;
                }
            }
        });
    
        mRestored = true;
    }
    
    /**
     * An interface for an owner of this @{code {@link SavedStateRegistry}
     * to perform state saving, it will call all registered providers and
     * merge with unconsumed state.
     *
     * @param outBundle Bundle in which to place a saved state
     */
    @MainThread
    void performSave(@NonNull Bundle outBundle) {
        Bundle components = new Bundle();
        if (mRestoredState != null) {
            components.putAll(mRestoredState);
        }
        for (Iterator<Map.Entry<String, SavedStateProvider>> it =
                mComponents.iteratorWithAdditions(); it.hasNext(); ) {
            Map.Entry<String, SavedStateProvider> entry1 = it.next();
            components.putBundle(entry1.getKey(), entry1.getValue().saveState());
        }
        outBundle.putBundle(SAVED_COMPONENTS_KEY, components);
    }
}

官方介绍,可以看到它是实际进行保存和恢复数据的地方。我们再看下它的performSave:这里会遍历mComponents,最后将components保存到outBundle中。我们看下mComponents的定义与使用:

private SafeIterableMap<String, SavedStateProvider> mComponents =
            new SafeIterableMap<>();
            
@MainThread
public void registerSavedStateProvider(@NonNull String key,
        @NonNull SavedStateProvider provider) {
    SavedStateProvider previous = mComponents.putIfAbsent(key, provider);
    if (previous != null) {
        throw new IllegalArgumentException("SavedStateProvider with the given key is"
                + " already registered");
    }
}

/**
 * Unregisters a component previously registered by the given {@code key}
 *
 * @param key a key with which a component was previously registered.
 */
@MainThread
public void unregisterSavedStateProvider(@NonNull String key) {
    mComponents.remove(key);
}

它是个map,用于存储SavedStateProvider。那SavedStateHandle又是怎么与它产生关联的呢?其实在SavedStateHandleController.create方法中有提及:

void attachToLifecycle(SavedStateRegistry registry, Lifecycle lifecycle) {
    if (mIsAttached) {
        throw new IllegalStateException("Already attached to lifecycleOwner");
    }
    mIsAttached = true;
    lifecycle.addObserver(this);
    registry.registerSavedStateProvider(mKey, mHandle.savedStateProvider());
}

通过registry.registerSavedStateProvider(mKey, mHandle.savedStateProvider());SavedStateHandlesavedStateProvider注册到registry

上边的源码可以看到,SavedStateRegistryController其实是持有了SavedStateRegistry的实例,所有的操作都是间接调用了SavedStateRegistry。我们回到ComponentActivity

@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 (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}

@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    Lifecycle lifecycle = getLifecycle();
    if (lifecycle instanceof LifecycleRegistry) {
        ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
    }
    super.onSaveInstanceState(outState);
    mSavedStateRegistryController.performSave(outState);
}
  • onCreate调用了mSavedStateRegistryController.performRestore(savedInstanceState);
  • onSaveInstanceState调用了mSavedStateRegistryController.performSave(outState);

总结

通过层层分析,我们可以有以下总结:

  • 其实SavedStateHandle最终也是通过ComponentActivityonSaveInstanceState(Bundle)实现了数据的保存与恢复
  • 对用户层只是提供了一个SavedStateHandle用于操作数据的保存与恢复,实际的实现全部隐藏在SavedStateRegistry中,它才是真正提供了这块的能力。
  • 假如使用了SavedStateHandle,假如希望保留数据,需要使用它提供的:getLiveData(@NonNull String key)setValue(T value)。因为它的成员mRegular就是用于存储在数据重建流程中要恢复的数据的。