截止到目前为止,JetpackNote源码分析的文章已经有四篇文章了,这一系列的文章个人初衷是想仔细研究一下Jetpack,最终使用Jetpack组件写一个Demo,上一篇已经分析了
LiveData
,本篇文章将分析ViewModel.java
Jetpack源码解析系列文章:git
1. Jetpack源码解析---看完你就知道Navigation是什么了?github
2. Jetpack源码解析---Navigation为何切换Fragment会重绘?app
3. Jetpack源码解析---用Lifecycles管理生命周期ide
4. Jetpack源码解析—LiveData的使用及工做原理函数
上篇咱们对LiveData
进行了分析,已清楚了它的主要做用,咱们再来温习一下:源码分析
LiveData是一个能够感知Activity、Fragment生命周期的数据容器。其自己是基于观察者模式设计的,当
LiveData
所持有的数据发生改变时,它会通知对应的界面所持有该数据的UI进行更新,而且LiveData
中持有Lifecycle
的引用,因此只会在LifecycleOwner
处于Active
的状态下通知数据改变,果数据改变发生在非 active 状态,数据会变化,可是不发送通知,等owner
回到 active 的状态下,再发送通知.post而
LiveData
配合今天所讲的ViewModel
使用起来真的是很是方便,接下来咱们开始分析:ui
简单来讲:ViewModel
是以关联生命周期的方式来存储和管理UI相关数据的类,即便configuration
发生改变(例如屏幕旋转),数据仍然能够存在不会销毁.this
举个例子来讲:咱们在开发中常常会遇到这种场景,当咱们的Activity和Fragment被销毁重建以后,它们中的数据将会丢失,而咱们通常的解决方案就是经过onSaveInstanceState()
中保存数据,而后在onCreate()
中恢复过来,可是当这些数据较大时或者数据可能又须要从新请求接口,这时候ViewModel就派上用场了,也就是说当咱们把数据保存在ViewModel中,无论Activity和Fragment被销毁了仍是屏幕旋转致使configuration发生了变化,保存在其中的数据依然存在。
不只如此,ViewModel还能够帮助咱们轻易的实现Fragment及Activity之间的数据共享和通讯,下面会详细介绍。
先来看一下官方给出的图:
图中展现了当一个Activity通过屏幕旋转后的生命周期状态改变,右侧则是ViewModel的生命周期状态。咱们能够看到ViewModel的生命周期并不会跟随着Activity的生命周期变化而变化,虽然ViewModel是由该Activity建立的。咱们会在源码分析部分再去看ViewModel的生命周期具体是怎样的。下面咱们看下ViewModel该怎样使用?
咱们参考官方Demo实现一个计时器的功能,而且演示当屏幕发生旋转时,计时器会不会从新启动:
DemoViewModel
class DemoViewModel : ViewModel() {
var time: Long? = null
var seekbarValue = MutableLiveData<Int>()
}
复制代码
ViewModelFragment
class ViewModelFragment : Fragment() {
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {
return inflater.inflate(R.layout.fragment_view_model, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val vm = ViewModelProviders.of(this).get(DemoViewModel::class.java)
if (vm.time == null) {
vm.time = SystemClock.elapsedRealtime()
}
chronometer.base = vm.time!!
chronometer.start()
btn_fragment_share.setOnClickListener {
findNavController().navigate(R.id.viewModelShareActivity)
}
}
}
复制代码
代码很简单,只是在ViewModel中存储了一个time
值,在fragment中启动计时器,当咱们旋转屏幕的时候你会发现,计时器的值并无变化,仍然按照旋转以前的数值进行计数。
在ViewModelShareActivity中展现了ViewModel中的数据进行Fragment数据共享的功能。
在以前的DemoViewModel中咱们存储了seekbar
的值,而后咱们看Fragment中是怎么实现的?
class DataShareFragment : Fragment() {
private lateinit var mViewModel: DemoViewModel
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {
mViewModel = ViewModelProviders.of(activity!!).get(DemoViewModel::class.java)
return inflater.inflate(R.layout.fragment_data_share, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
subscribeSeekBar()
}
private fun subscribeSeekBar() {
// 监听SeekBar改变ViewModel的中的值
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) {
mViewModel.seekbarValue.value = progress
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
// 当ViewModel中的值发生变化时,更新SeekBar
activity?.let {
mViewModel.seekbarValue.observe(it, Observer<Int> { value ->
if (value != null) {
seekBar.progress = value
}
})
}
}
}
复制代码
看代码其实挺简单的,只作了两个操做:
一样,当旋转屏幕以后,SeekBar的值也不会改变。到这里ViewModel的基本使用方式咱们已经了解了,接下来咱们来分析一下它具体是怎么实现的?
没错,又到了源码分析的部分了,相信不少童鞋也都比较不喜欢源码的部分,包括我也是,以前很不肯意去看源码,可是当你尝试看了一些源码以后,你会发现颇有意思的,由于有些东西你是有必要去分析源码实现的,这是做为一个开发者必备的基本的素质,并且当你使用一个组件的时候,一步一步的跟着代码走,慢慢的分析了整个的组件设计方式,最后站在开发这个组件的角度,去看他的设计思想和一些模式的时候,对本身自己也是一个很大的提升,因此我真的建议有兴趣的能够跟着本身的思路一步一步的看下源码。好了废话很少说。
ViewModelProviders
在使用VM的时候通常都经过val vm = ViewModelProviders.of(this).get(DemoViewModel::class.java)
去建立,具体来看一下of方法:
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment, @Nullable Factory factory) {
Application application = checkApplication(checkActivity(fragment));
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(fragment.getViewModelStore(), factory);
}
复制代码
of方法经过ViewModelProvider中的一个单例AndroidViewModelFactory建立了Factory帮助咱们去建立VM,而且返回了一个ViewModelProvider。你们注意一下第一个参数fragment.getViewModelStore()
,这个ViewModelStore是什么呢?接着看
public class ViewModelStore {
private final HashMap<String, ViewModel> mMap = new HashMap<>();
//存储VM
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();
}
}
复制代码
其实就是一个存储VM的容器,里面经过HashMap进行存和取。
下面咱们看建立VM时的get()
方法
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
//在ViewModelStore中拿到VM实例
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
//noinspection unchecked
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
//工厂建立VM,并保存VM
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
} else {
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
//noinspection unchecked
return (T) viewModel;
}
复制代码
get()
方法就是获取VM实例的过程,若是VM不存在,则经过工厂去建立实例。具体工厂建立实现:
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);
}
.......
}
return super.create(modelClass);
}
}
复制代码
这个工厂就很简单了,就是经过反射来建立VM实例。
到这里VM的建立过程就差很少了,而咱们发现他并无和生命周期有什么相关的东西,或者说VM是怎样保证的的数据不被销毁的呢?看了网上的一些文章,不少都说在of
方法的时候传入了Fragment,而且经过HolderFragment持有ViewModelStore对象等等……好比:
可是在我这里发现跟他们的都不同,我搜了一下ViewModelStores,发现它已经‘退役’了。
而且它的注释也告诉了咱们它的继承者:
也就是咱们在of()
方法中的:
也就是说谷歌已经将ViewModelStore集成到了Fragment中,一块儿去看一下吧:
Fragment.java
@NonNull
@Override
public ViewModelStore getViewModelStore() {
if (mFragmentManager == null) {
throw new IllegalStateException("Can't access ViewModels from detached fragment");
}
return mFragmentManager.getViewModelStore(this);
}
FragmentManagerImpl.java
private FragmentManagerViewModel mNonConfig;
......
@NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
return mNonConfig.getViewModelStore(f);
}
复制代码
咱们能够看到代码到了咱们熟悉的FragmentManagerImpl,它的里面持有了一个FragmentManagerViewModel实例,进去看看这个是个什么东西:
FragmentManagerViewModel.java
class FragmentManagerViewModel extends ViewModel {
//建立FragmentVM的工厂
private static final ViewModelProvider.Factory FACTORY = new ViewModelProvider.Factory() {
@NonNull
@Override
@SuppressWarnings("unchecked")
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
FragmentManagerViewModel viewModel = new FragmentManagerViewModel(true);
return (T) viewModel;
}
};
//从viewModelProvider中获取FragmentVM实例
@NonNull
static FragmentManagerViewModel getInstance(ViewModelStore viewModelStore) {
ViewModelProvider viewModelProvider = new ViewModelProvider(viewModelStore,
FACTORY);
return viewModelProvider.get(FragmentManagerViewModel.class);
}
//非中断的Fragment集合
private final HashSet<Fragment> mRetainedFragments = new HashSet<>();
private final HashMap<String, FragmentManagerViewModel> mChildNonConfigs = new HashMap<>();
private final HashMap<String, ViewModelStore> mViewModelStores = new HashMap<>();
private final boolean mStateAutomaticallySaved;
// Only used when mStateAutomaticallySaved is true
private boolean mHasBeenCleared = false;
// Only used when mStateAutomaticallySaved is false
private boolean mHasSavedSnapshot = false;
FragmentManagerViewModel(boolean stateAutomaticallySaved) {
mStateAutomaticallySaved = stateAutomaticallySaved;
}
//添加非中断Fragment
boolean addRetainedFragment(@NonNull Fragment fragment) {
return mRetainedFragments.add(fragment);
}
@NonNull
Collection<Fragment> getRetainedFragments() {
return mRetainedFragments;
}
//是否改销毁
boolean shouldDestroy(@NonNull Fragment fragment) {
if (!mRetainedFragments.contains(fragment)) {
// Always destroy non-retained Fragments
return true;
}
if (mStateAutomaticallySaved) {
// If we automatically save our state, then only
// destroy a retained Fragment when we've been cleared
return mHasBeenCleared;
} else {
// Else, only destroy retained Fragments if they've
// been reaped before the state has been saved
return !mHasSavedSnapshot;
}
}
boolean removeRetainedFragment(@NonNull Fragment fragment) {
return mRetainedFragments.remove(fragment);
}
//获取VMStore
@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;
}
//销毁并清空VM
void clearNonConfigState(@NonNull Fragment f) {
if (FragmentManagerImpl.DEBUG) {
Log.d(FragmentManagerImpl.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);
}
}
复制代码
看代码咱们发现它继承了VM,而且里面保存了VMStore,也就是说保存了VM,同时清空的操做也在这里面:clearNonConfigState()
ViewModelStore.java
/** * 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();
}
复制代码
那么究竟是何时来清空VM的呢?也就是说clear()
是何时调用的呢?查看源码咱们发现有两处:
clearNonConfigState()
方法,而这个方法只在一个地方被调用了:if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
boolean beingRemoved = f.mRemoving && !f.isInBackStack();
if (beingRemoved || mNonConfig.shouldDestroy(f)) {
boolean shouldClear;
if (mHost instanceof ViewModelStoreOwner) {
shouldClear = mNonConfig.isCleared();
} else if (mHost.getContext() instanceof Activity) {
Activity activity = (Activity) mHost.getContext();
shouldClear = !activity.isChangingConfigurations();
} else {
shouldClear = true;
}
//Fragment正在被移除或者应该清空的状态下
if (beingRemoved || shouldClear) {
mNonConfig.clearNonConfigState(f);
}
f.performDestroy();
dispatchOnFragmentDestroyed(f, false);
} else {
f.mState = Fragment.INITIALIZING;
}
复制代码
这个方法是在FragmentManagerImpl.java中的
moveToState
方法里面的,这个方法是跟随着Fragment的生命周期的,当这个方法被调用时,判断两个状态beingRemoved
和shoudClear
而后调用clear()
方法。关于moveToState()
能够查看这篇文章:Fragment之底层关键操做函数moveToState
getLifecycle().addObserver(new GenericLifecycleObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {//不是改变状态配置的
getViewModelStore().clear();
}
}
}
});
复制代码
关于ComponentActivity,若是有看过以前我分析过的关于Lifecycles的应该对它有所了解3. Jetpack源码解析---用Lifecycles管理生命周期。FragmentActivity继承了它,而ComponentActivity里面经过Lifecycles观察生命周期,当接受到ON_DESTROY的事件时,清空VM。
分析完源码以后,咱们来总结一下整个流程:
ViewModelProviders.of(this).get(DemoViewModel::class.java)
建立VMof()
方法中传入 fragment.getViewModelStore()
而且返回VMProvidersgetViewModelStore()
,持有FragmentManagerViewModel对象clearNonConfigState()
,同时在ViewModelStore中clear()
了ViewModel的value值ON_DESTROY
的事件时同时并非因为configuration
发生变化时才会执行clear()
操做;另一处是在moveToState()
方法中,知足beingRemoved
和shouldClear
状态也会清空VM好了 整个流程就是这样了,并无特别深刻的去分析,可是基本的原理咱们已经清楚了,Demo中也只是简单的使用了VM。
JetPack源码分析系列文章到这里应该就结束了,后面还有Paging、WorkManager、Room,以及Camera2和ViewPager2,这些目前暂时不分析了,可是也会出基本的使用和简单的分析,一共5篇源码分析,文章中的Demo我写了一个APP—JetpackNote,里面有基本的Demo例子,和文章的分析;一直也没有提到是由于功能还不完善,我会尽快完善它的,也但愿有什么意见的小伙伴能够和我沟通交流。
Github源码地址在: