ViewModel
概念
负责存储Activity Fragment一些信息
viewModel 都放在viewModelStore里面去了
CompenentActivity 继承关系
ViewModelStoreOwner来源的地方 解释一个Activity只有一个viewModelStoreOwer
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
ContextAware,
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner,
ActivityResultRegistryOwner,
ActivityResultCaller,
OnConfigurationChangedProvider,
OnTrimMemoryProvider,
OnNewIntentProvider,
OnMultiWindowModeChangedProvider,
OnPictureInPictureModeChangedProvider,
MenuHost</span></span>
加入
Activity 绑定ViewModel
@Override
public LoraPageViewModel getViewModel() {
return new ViewModelProvider(getActivity(),
new LoraPageViewModel.LoraPageViewModelFactory())
.get(LoraPageViewModel.class);
}
//无参构造方法
gdOperationViewModel = new ViewModelProvider(this).get(GdOperationViewModel.class);
viewModelProvider 构造方法
public constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
owner.viewModelStore,
factory,
defaultCreationExtras(owner)
)
get store.put(key, it)
@Suppress("UNCHECKED_CAST")
@MainThread
public open operator fun <T : ViewModel> get(key: String, modelClass: Class<T>): T {
val viewModel = store[key] //store is 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) }// it is viewModel
}
共用
一个Activity一个viewModelStore 如果是同一个AViewModel 在同一个Activity get两次会从map里面取
ViewModelStoreOwner 被Activity Fragment实现了
AFragment 在AActivity里面 都by viewModel 这两个viewModel不一样
移除
ComponentActivity
//onDestory 移除ViewModel
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
//noinspection ConstantConditions
if (lifecycle == null) {
throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
+ "constructor. Please make sure you are lazily constructing your Lifecycle "
+ "in the first call to getLifecycle() rather than relying on field "
+ "initialization.");
}
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();
}
}
}
});
mSavedStateRegistryController.performAttach();
enableSavedStateHandles(this);
}
Fragment Activity ViewModel
Fragment ComponentActivity 都是继承ViewModelStoreOwer
public class Fragment implements ViewModelStoreOwner
public class ComponentActivity implements ViewModelStoreOwner,
所以Activity下的Fragment可能用的不是一个ViewModelStoreOwner 主要看使用ViewModelProvider 传参
如果传getActivity()就和Activity共用一个ViewModelStore 如果传this就是自己单独一个ViewModelStore
@Override
public LightValueViewModel getViewModel() {
RequestDevBean requestDevBean = adjustLightPageData.coverToRequestDev(QueryLightEnum.ONE.getType());
return new ViewModelProvider(this,
new LightValueViewModel.MapLightValueViewModelFactory(requestDevBean))
.get(LightValueViewModel.class);
}
public interface ViewModelStoreOwner {
/**
* Returns owned {@link ViewModelStore}
*
* @return a {@code ViewModelStore}
*/
@NonNull
ViewModelStore getViewModelStore();
}
ViewModelStore
public final void clear() {
for (ViewModel vm : mMap.values()) {
vm.clear();
}
mMap.clear();//mMap 是HashMap
}