viewmodel是如果实现数据存储
viewmodel应用于多界面之间对数据的操作应用,通过对源码进行解析

//传入当前页面
public static ViewModelProviderof(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
//获取到该页面的上下问
Application application =checkApplication(activity);
if (factory ==null) {
//工厂为空时,创建一个工厂
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
//这里将页面的一个集合和工厂传递给ViewModelProvider(这里有个疑问页面的集合是来源于哪里,到下面的时候,我来解释)
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
在of方法中我们获取到了ViewModelProvider对象,那么可以通过该对象去调用get()



这里就是获取到一个modelclass的一个实例,那么有个疑问就是既然把viewmodel存入到集合中,那么这个集合在哪里?
sdk26之后我们来看一下activity的基类ComponentActivity

通过ComponentActivity中onRetainNonConfigurationInstance()我们找到了viewModelStore,那么它属于哪个类呢

也就是说这个静态代码块的生命周期是依附于application的,所以在整个项目中通过对应的viewmodel就可获取到集合中对应viewmodel所存储的数据,不会受到单页面销毁的影响
观察者是如何监听viewmodel中的数据变化的
我们来看一段代码

@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
assertMainThread("observe");
//observer是在activity可见的情况下进行监听,如果activity被销毁,监听结束
if (owner.getLifecycle().getCurrentState() ==DESTROYED) {
// ignore
return;
}
////将观察者和activity放到一个边界中
LifecycleBoundObserver wrapper =new LifecycleBoundObserver(owner, observer);
//将边界扔到了一个集合里
ObserverWrapper existing =mObservers.putIfAbsent(observer, wrapper);
if (existing !=null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+" with different lifecycles");
}
if (existing !=null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}
我们在哪里获取到该边界集合,
观察者的作用在于观察viewmodel数据发生改变,数据的改变是在viewmodel赋值时产生的,那么我们去找viewmodel的赋值操作


viewmodel中的livedata包含有postValue()和setValue()都是用于赋值操作,那么我们先来看setValue(T value)



postValue()的底层开启一个子线程,子线程中也是调用的setValue()方法


网友评论