一、ViewModel介绍
ViewModel属于lifecycle(生命周期感知型组件)中的一员,通常与LiveData、DataBinding一起使用,它们是MVVM架构的重要成员。ViewModel类旨在以注重生命周期的方式存储和管理界面相关的数据。ViewModel的生命周期比Activty的生命周期长,只有Activity真的销毁时ViewModel的生命周期才会结束;比如Activity旋转和按home键的销毁重建并不会导致ViewModel销毁。另外ViewModel是将数据存储在内存中所以能够比onSaveInstanceState反序列化存储的数据多,因为Bundle本身就不能存储大量的数据。
二、ViewModel使用
ViewModel 是一个抽象类必须继承ViewModel实现自己的子类
public class TestViewModel extends ViewModel {
MutableLiveData<String> data = new MutableLiveData<>();
public MutableLiveData<String> getData() {
return data;
}
}
Activity中创建ViewModel
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//创建ViewModel提供者,this必须是实现了ViewModelStoreOwner
ViewModelProvider viewModelProvider = new ViewModelProvider(this);
//通过get方法获取自己定义的ViewModel
TestViewModel testViewModel = viewModelProvider.get(TestViewModel.class);
//观察数据变化
testViewModel.getData().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
// update ui.
Log.d(TAG, "onChanged: "+s);
}
});
}
三、ViewModel源码分析
从上面ViewModel
的使用中可以看到需要先创建ViewModelProvider
然后使用其get方法获取想要获取的ViewModel。那么先看下ViewModelProvider源码。
/**
* Creates `ViewModelProvider`. This will create `ViewModels`
* and retain them in a store of the given `ViewModelStoreOwner`.
*
*
* This method will use the
* [default factory][HasDefaultViewModelProviderFactory.getDefaultViewModelProviderFactory]
* if the owner implements [HasDefaultViewModelProviderFactory]. Otherwise, a
* [NewInstanceFactory] will be used.
*/
public constructor(
owner: ViewModelStoreOwner
) : this(owner.viewModelStore, defaultFactory(owner), defaultCreationExtras(owner))
/**
* Creates `ViewModelProvider`, which will create `ViewModels` via the given
* `Factory` and retain them in a store of the given `ViewModelStoreOwner`.
*
* @param owner a `ViewModelStoreOwner` whose [ViewModelStore] will be used to
* retain `ViewModels`
* @param factory a `Factory` which will be used to instantiate
* new `ViewModels`
*/
public constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
owner.viewModelStore,
factory,
defaultCreationExtras(owner)
)
/**
* Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or
* an activity), associated with this `ViewModelProvider`.
*
*
* The created ViewModel is associated with the given scope and will be retained
* as long as the scope is alive (e.g. if it is an activity, until it is
* finished or process is killed).
*
* @param modelClass The class of the ViewModel to create an instance of it if it is not
* present.
* @return A ViewModel that is an instance of the given type `T`.
* @throws IllegalArgumentException if the given [modelClass] is local or anonymous class.
*/
@MainThread
public open operator fun <T : ViewModel> get(modelClass: Class<T>): T {
val canonicalName = modelClass.canonicalName
?: throw IllegalArgumentException("Local and anonymous classes can not be ViewModels")
return get("$DEFAULT_KEY:$canonicalName", modelClass)
}
@Suppress("UNCHECKED_CAST")
@MainThread
public open operator fun <T : ViewModel> get(key: String, modelClass: Class<T>): T {
//store是ViewModelStore对象
val viewModel = store[key]
//如果从ViewModelStore获取到,直接返回
if (modelClass.isInstance(viewModel)) {
(factory as? OnRequeryFactory)?.onRequery(viewModel)
return viewModel as T
} else {
@Suppress("ControlFlowWithEmptyBody")
if (viewModel != null) {
// TODO: log a warning.
}
}
val extras = MutableCreationExtras(defaultCreationExtras)
extras[VIEW_MODEL_KEY] = key
// AGP has some desugaring issues associated with compileOnly dependencies so we need to
// fall back to the other create method to keep from crashing.
return try {
//不存在则创建
factory.create(modelClass, extras)
} catch (e: AbstractMethodError) {
factory.create(modelClass)
}.also { store.put(key, it) }//保存ViewModel
}
ViewModelStore
ViewModelStore 就是一个包含Map的存储VIewModel的类
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());
}
/**
* 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();
}
}
可以看到ViewModelProvider
创建时传入了一个ViewModelStoreOwner
对象,这个对象Activity和Fragment已经帮我们实现了。ViewModelStoreOwner是一个帮我们保存ViewModel的类,那么我们通过源码分析下ViewModelStoreOwner怎么帮助我们恢复ViewModel的。
public interface ViewModelStoreOwner {
/**
* Returns owned {@link ViewModelStore}
*
* @return a {@code ViewModelStore}
*/
@NonNull
ViewModelStore getViewModelStore();
}
ComponentActivity
当Activity配置变化时调用,此时会调用onRetainNonConfigurationInstance方法保存ViewModelStoreOwner,获取时再从保存地方返回。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
ContextAware,
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner,
ActivityResultRegistryOwner,
ActivityResultCaller,
OnConfigurationChangedProvider,
OnTrimMemoryProvider,
OnNewIntentProvider,
OnMultiWindowModeChangedProvider,
OnPictureInPictureModeChangedProvider,
MenuHost {
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
}
//Activity销毁时清除ViewModelStore
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
// Clear out the available context
mContextAwareHelper.clearAvailableContext();
// And clear the ViewModelStore
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
}
//当Activity配置变化时调用,此时会调用onRetainNonConfigurationInstance方法
@Override
@Nullable
@SuppressWarnings("deprecation")
public final Object onRetainNonConfigurationInstance() {
// Maintain backward compatibility.
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
//getViewModel方法没有被调用时viewModelStore == null
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;
}
//保存viewModelStore
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
@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.");
}
ensureViewModelStore();
return mViewModelStore;
}
//获取保存的mViewModelStore ,如果保存的mViewModelStore == null则创建一个实例。
void ensureViewModelStore() {
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
}