class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel = ViewModelProvider(this , ViewModelProvider.NewInstanceFactory()).get(MyViewModel::class.java)
}
}
第一步:创建 ViewModelProvider , 拿到 ViewModelStoreOwner(ComponentActivity) 的 ViewModelStore , 如果有横竖屏切换,则拿上一次的 ViewModelStore , 否则如果为空 则创建 ViewModelStore
ViewModelProvider.kt
public constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
owner.viewModelStore, // 拿到 ViewModelStoreOwner(ComponentActivity) 的 viewModelStore
factory,
defaultCreationExtras(owner)
)
ComponentActivity.kt
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();
}
}
}
// 实际返回的是 NonConfigurationInstances
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
}
第二步 : 通过 ViewModelStore 创建、保存、获取 ViewModel
public open operator fun <T : ViewModel> get(key: String, modelClass: Class<T>): T {
val viewModel = store[key]
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) }
}
其他:
Activity onDestroy 时 , 判断如果不是 configChange , 则调用
ViewModelStore.clear() ,
---> ViewModel.clear()
--> ViewModel.onClear()