ViewModel 创建
val viewModel = ViewModelProvider(activity, factory).get(MyViewModel::class.java)
ViewModelProvider.java
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
if (mFactory instanceof OnRequeryFactory) {
((OnRequeryFactory) mFactory).onRequery(viewModel);
}
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
} else {
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
viewModel 来自owner.getViewModelStore(),也就是ComponentActivity.mViewModelStore,mViewModelStore是类似于Map的一个东西。
ComponentActivity.java
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
}
接下来分2个方向,第一个是getViewModelStore(),第二个是isChangingConfigurations()
先讲getViewModelStore()
ComponentActivity.java
@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.");
}
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
mViewModelStore 来自于NonConfigurationInstances的viewModelStore
Activity.java
@Nullable
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
看一下这个getLastNonConfigurationInstance的调用
ComponentActivity.java
@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
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;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
以下是调用顺序
#Activity初次启动
onCreate
- Activity
- ViewModel
onStart
onResume
#屏幕旋转
onPause
onStop
onRetainNonConfigurationInstance
onDestroy
onCreate
- Activity -Activity实例不同
- ViewModel -ViewModel实例相同
onStart
onResume
所以每次屏幕旋转时都会调用onRetainNonConfigurationInstance。去保存下来,这次应该深究一下保存的逻辑。
LocalActivityManager.java
public HashMap<String,Object> dispatchRetainNonConfigurationInstance() {
HashMap<String,Object> instanceMap = null;
final int N = mActivityArray.size();
for (int i=0; i<N; i++) {
LocalActivityRecord r = mActivityArray.get(i);
if ((r != null) && (r.activity != null)) {
Object instance = r.activity.onRetainNonConfigurationInstance();
if (instance != null) {
if (instanceMap == null) {
instanceMap = new HashMap<String,Object>();
}
instanceMap.put(r.id, instance);
}
}
}
return instanceMap;
}
Activity.java
@UnsupportedAppUsage
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
mLastNonConfigurationInstances = lastNonConfigurationInstances;
}
所以在旋转屏幕的时候getViewModelStore() 不会被删掉,会被保留下来。
接下来看isChangingConfigurations()
指向Activity.mChangingConfigurations
默认为false,默认是需要清除的,需要改成true。
ActivityThread.java
@Override
public void handleRelaunchActivity(ActivityClientRecord tmp,
PendingTransactionActions pendingActions) {
...
r.activity.mChangingConfigurations = true;
...
}
然后我们正向推。如果到handleRelaunchActivity 就是成功的
ActivityThread.java
class H extends Handler {
public void handleMessage(Message msg) {
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
}
}
还是ActivityThread.java
ActivityThread.java
private void handleRelaunchActivityLocally(IBinder token) {
...
executeTransaction(transaction);
}
然后看executeTransaction.java ActivityThread的父类
executeTransaction.java
@VisibleForTesting
public void executeTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
getTransactionExecutor().execute(transaction);
transaction.recycle();
}
getTransactionExecutor() -> TransactionExecutor类
TransactionExecutor.java
public void execute(ClientTransaction transaction) {
..
executeCallbacks(transaction);
..
}
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
ClientTransactionItem 类的实现类 是ActivityRelaunchItem.java
ActivityRelaunchItem.java
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
if (mActivityClientRecord == null) {
if (DEBUG_ORDER) Slog.d(TAG, "Activity relaunch cancelled");
return;
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
client.handleRelaunchActivity(mActivityClientRecord, pendingActions);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
?ClientTransactionHandler 是ActivityThread的父类
ActivityThread.java
@Override
public void handleRelaunchActivity(ActivityClientRecord tmp,
PendingTransactionActions pendingActions) {
...
r.activity.mChangingConfigurations = true;
...
}
所以形成闭环了
|