ViewModel
ViewModelProviders
1 2 3
| class TestViewModel extends ViewModel
TestViewModel test = ViewModelProviders.of(this).get(TestViewModel.class);
|
在ViewModelProviders中会创建ViewModelProvider,通过ViewModelProvider来管理ViewModel。
1 2 3 4 5 6 7 8 9 10
| @NonNull @MainThread public static ViewModelProvider of(@NonNull FragmentActivity activity, @Nullable Factory factory) { Application application = checkApplication(activity); if (factory == null) { factory = AndroidViewModelFactory.getInstance(application); }
return new ViewModelProvider(ViewModelStores.of(activity), (Factory)factory); }
|
ViewModelProvider中的核心要素只有ViewModelProvider.Factory和ViewModelStore。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class ViewModelProvider { private final ViewModelProvider.Factory mFactory; private final ViewModelStore mViewModelStore; @NonNull @MainThread public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) { ViewModel viewModel = this.mViewModelStore.get(key); if (modelClass.isInstance(viewModel)) { return viewModel; } else { if (viewModel != null) { }
viewModel = this.mFactory.create(modelClass); this.mViewModelStore.put(key, viewModel); return viewModel; } } }
|
在ViewModelProvider.get时,先从mViewModelStore中取,取不到就通过mFactory创建。下面分别是2个
Factory中的创建方式,当有包含Application构造函数时,注入mApplication,不包含则直接无参数构造。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public static class NewInstanceFactory implements ViewModelProvider.Factory{ @NonNull public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { try { return (ViewModel)modelClass.newInstance(); } catch (InstantiationException var3) { throw new RuntimeException("Cannot create an instance of " + modelClass, var3); } catch (IllegalAccessException var4) { throw new RuntimeException("Cannot create an instance of " + modelClass, var4); } } } public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory { @NonNull public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (AndroidViewModel.class.isAssignableFrom(modelClass)) { try { return (ViewModel)modelClass.getConstructor(Application.class).newInstance(this.mApplication); } catch (NoSuchMethodException var3) { throw new RuntimeException("Cannot create an instance of " + modelClass, var3); } catch (IllegalAccessException var4) { throw new RuntimeException("Cannot create an instance of " + modelClass, var4); } catch (InstantiationException var5) { throw new RuntimeException("Cannot create an instance of " + modelClass, var5); } catch (InvocationTargetException var6) { throw new RuntimeException("Cannot create an instance of " + modelClass, var6); } } else { return super.create(modelClass); } } }
|
通过下图可看到ViewModelStore可来源于FragmentActivity,非FragmentActivity可以通过ViewModelStores._of_(activity)
中的HolderFragment
来注入,原理同后文的ReportFragment
。
#### LiveData.postValue
可在子线程中触发,最终使用的是setValue,如果发送数据过快,存在数据丢失可能,每次从mPendingData中取最新数据。
在post时将数据复制到mPendingData,送入主循环队列,后面发送数据时,从mPendingData缓存中取数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| protected void postValue(T value) { boolean postTask; synchronized(this.mDataLock) { postTask = this.mPendingData == NOT_SET; this.mPendingData = value; }
if (postTask) { ArchTaskExecutor.getInstance().postToMainThread(this.mPostValueRunnable); } }
this.mPostValueRunnable = new Runnable() { public void run() { Object newValue; synchronized(LiveData.this.mDataLock) { newValue = LiveData.this.mPendingData; LiveData.this.mPendingData = LiveData.NOT_SET; }
LiveData.this.setValue(newValue); } };
|
LiveData.setValue
在主线程中执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| @MainThread protected void setValue(T value) { assertMainThread("setValue"); ++this.mVersion; this.mData = value; this.dispatchingValue((LiveData.ObserverWrapper)null); }
private void dispatchingValue(@Nullable LiveData<T>.ObserverWrapper initiator) { if (this.mDispatchingValue) { this.mDispatchInvalidated = true; } else { this.mDispatchingValue = true;
do { this.mDispatchInvalidated = false; if (initiator != null) { this.considerNotify(initiator); initiator = null; } else { IteratorWithAdditions iterator = this.mObservers.iteratorWithAdditions();
while(iterator.hasNext()) { this.considerNotify((LiveData.ObserverWrapper)((Entry)iterator.next()).getValue()); if (this.mDispatchInvalidated) { break; } } } } while(this.mDispatchInvalidated);
this.mDispatchingValue = false; } } private void considerNotify(LiveData<T>.ObserverWrapper observer) { if (observer.mActive) { if (!observer.shouldBeActive()) { observer.activeStateChanged(false); } else if (observer.mLastVersion < this.mVersion) { observer.mLastVersion = this.mVersion; observer.mObserver.onChanged(this.mData); } } }
|
setValue主要分3步:
- ++this.mVersion;
- 取出mObservers分发值
- 根据当前条件分发值
分发值的条件:
- observer处于Active
- observer.mLastVersion < this.mVersion
- 至少处于started之后的生命周期状态,observer.shouldBeActive(),也就是started和resumed状态下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| boolean shouldBeActive() { return this.mOwner.getLifecycle().getCurrentState().isAtLeast(State.STARTED); } public static enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED;
private State() { }
public boolean isAtLeast(@NonNull Lifecycle.State state) { return this.compareTo(state) >= 0; } }
|
LiveData.observe和observeForever
二者都是将observer包装后放入mObservers中。不同的是observe使用的是LifecycleBoundObserver,当生命周期状态为DESTROYED时,将自己从mObservers移除;observeForever使用的是AlwaysActiveObserver,并将激活状态一直设置为true。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @MainThread public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) { if (owner.getLifecycle().getCurrentState() != State.DESTROYED) { LiveData<T>.LifecycleBoundObserver wrapper = new LiveData.LifecycleBoundObserver(owner, observer); LiveData<T>.ObserverWrapper existing = (LiveData.ObserverWrapper)this.mObservers.putIfAbsent(observer, wrapper); if (existing != null && !existing.isAttachedTo(owner)) { throw new IllegalArgumentException("Cannot add the same observer with different lifecycles"); } else if (existing == null) { owner.getLifecycle().addObserver(wrapper); } } }
@MainThread public void observeForever(@NonNull Observer<T> observer) { LiveData<T>.AlwaysActiveObserver wrapper = new LiveData.AlwaysActiveObserver(observer); LiveData<T>.ObserverWrapper existing = (LiveData.ObserverWrapper)this.mObservers.putIfAbsent(observer, wrapper); if (existing != null && existing instanceof LiveData.LifecycleBoundObserver) { throw new IllegalArgumentException("Cannot add the same observer with different lifecycles"); } else if (existing == null) { wrapper.activeStateChanged(true); } }
|
Lifecycle
在SupportActivity中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class SupportActivity{ private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } public Lifecycle getLifecycle() { return this.mLifecycleRegistry; } }
public class ReportFragment extends Fragment { public static void injectIfNeededIn(Activity activity) { FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag("android.arch.lifecycle.LifecycleDispatcher.report_fragment_tag") == null) { manager.beginTransaction().add(new ReportFragment(), "android.arch.lifecycle.LifecycleDispatcher.report_fragment_tag").commit(); manager.executePendingTransactions(); }
} }
|
SupportActivity onCreate时注入ReportFragment,用来监听生命周期。
在ReportFragment中,通过添加Fragment到Activity中来实现对Activity生命周期的捕捉(类似的有权限申请)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class ReportFragment extends Fragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); this.dispatchCreate(this.mProcessListener); this.dispatch(Event.ON_CREATE); }
public void onStart() { super.onStart(); this.dispatchStart(this.mProcessListener); this.dispatch(Event.ON_START); }
public void onResume() { super.onResume(); this.dispatchResume(this.mProcessListener); this.dispatch(Event.ON_RESUME); }
public void onPause() { super.onPause(); this.dispatch(Event.ON_PAUSE); }
public void onStop() { super.onStop(); this.dispatch(Event.ON_STOP); }
public void onDestroy() { super.onDestroy(); this.dispatch(Event.ON_DESTROY); this.mProcessListener = null; } private void dispatch(Event event) { Activity activity = this.getActivity(); if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner)activity).getLifecycle().handleLifecycleEvent(event); } else { if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner)activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry)lifecycle).handleLifecycleEvent(event); } }
} } }
|
最终生命周期的处理实现在LifecycleRegistryOwner中,也就是 SupportActivity中的mLifecycleRegistry。
在LifecycleRegistryOwner中,当前后状态相同是,不会触发状态变更。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class LifecycleRegistry extends Lifecycle { public void handleLifecycleEvent(@NonNull Event event) { State next = getStateAfter(event); this.moveToState(next); }
private void moveToState(State next) { if (this.mState != next) { this.mState = next; if (!this.mHandlingEvent && this.mAddingObserverCounter == 0) { this.mHandlingEvent = true; this.sync(); this.mHandlingEvent = false; } else { this.mNewEventOccurred = true; } } }
private void sync() { LifecycleOwner lifecycleOwner = (LifecycleOwner)this.mLifecycleOwner.get(); if (lifecycleOwner == null) { Log.w("LifecycleRegistry", "LifecycleOwner is garbage collected, you shouldn't try dispatch new events from it."); } else { while(!this.isSynced()) { this.mNewEventOccurred = false; if (this.mState.compareTo(((LifecycleRegistry.ObserverWithState)this.mObserverMap.eldest().getValue()).mState) < 0) { this.backwardPass(lifecycleOwner); }
Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState> newest = this.mObserverMap.newest(); if (!this.mNewEventOccurred && newest != null && this.mState.compareTo(((LifecycleRegistry.ObserverWithState)newest.getValue()).mState) > 0) { this.forwardPass(lifecycleOwner); } }
this.mNewEventOccurred = false; } } }
|
ProcessLifecycleOwnerInitializer
1 2 3 4 5 6 7 8 9 10
| public class ProcessLifecycleOwnerInitializer extends ContentProvider { public ProcessLifecycleOwnerInitializer() { }
public boolean onCreate() { LifecycleDispatcher.init(this.getContext()); ProcessLifecycleOwner.init(this.getContext()); return true; } }
|
LifecycleDispatcher
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class LifecycleDispatcher { static void init(Context context) { if (!sInitialized.getAndSet(true)) { ((Application)context.getApplicationContext()).registerActivityLifecycleCallbacks(new LifecycleDispatcher.DispatcherActivityCallback()); } }
}
static class DispatcherActivityCallback{ public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (activity instanceof FragmentActivity) { ((FragmentActivity)activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(this.mFragmentCallback, true); }
ReportFragment.injectIfNeededIn(activity); } }
|
通过对application生命周期注册,在onActivityCreated时注入ReportFragment。
如果是FragmentActivity,还会registerFragmentLifecycleCallbacks。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| static class FragmentCallback extends FragmentLifecycleCallbacks { FragmentCallback() { }
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) { LifecycleDispatcher.dispatchIfLifecycleOwner(f, Event.ON_CREATE); if (f instanceof LifecycleRegistryOwner) { if (f.getChildFragmentManager().findFragmentByTag("android.arch.lifecycle.LifecycleDispatcher.report_fragment_tag") == null) { f.getChildFragmentManager().beginTransaction().add(new LifecycleDispatcher.DestructionReportFragment(), "android.arch.lifecycle.LifecycleDispatcher.report_fragment_tag").commit(); }
} }
public void onFragmentStarted(FragmentManager fm, Fragment f) { LifecycleDispatcher.dispatchIfLifecycleOwner(f, Event.ON_START); }
public void onFragmentResumed(FragmentManager fm, Fragment f) { LifecycleDispatcher.dispatchIfLifecycleOwner(f, Event.ON_RESUME); } }
|
主要是将onFragmentCreated、onFragmentStarted、onFragmentResumed分别分发为ON_CREATE、ON_START、ON_RESUME。
ProcessLifecycleOwner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class ProcessLifecycleOwner{ static void init(Context context) { sInstance.attach(context); } void attach(Context context) { this.mHandler = new Handler(); this.mRegistry.handleLifecycleEvent(Event.ON_CREATE); Application app = (Application)context.getApplicationContext(); app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() { public void onActivityCreated(Activity activity, Bundle savedInstanceState) { ReportFragment.get(activity).setProcessListener(ProcessLifecycleOwner.this.mInitializationListener); }
public void onActivityPaused(Activity activity) { ProcessLifecycleOwner.this.activityPaused(); }
public void onActivityStopped(Activity activity) { ProcessLifecycleOwner.this.activityStopped(); } }); } }
|
主要用处是将ProcessListener(ActivityInitializationListener)注入到对应activity的ReportFragment中。而ActivityInitializationListener中主要包含常用的3个生命周期状态。当ReportFragment中处理什么周期时,会回调这3个方法。
1 2 3 4 5
| interface ActivityInitializationListener { void onCreate(); void onStart(); void onResume(); }
|
总结
ViewModel
- ViewModel使用反射的形式创建,获取时先从ViewModelStores缓存中获取,没找到则通过Factory创建
- 非FragmentActivity类或没实现ViewModelStoreOwner,可通过HolderFragment注入ViewModelStores
- LiveData中postValue可在子线程使用,最终会在主线程调用setValue来分发数据
- LiveData中postValue时,执行setValue时,每次取mPendingData,因此如果postValue过快,会导致前面的数据会被后面的覆盖。
- 分发数据时的条件有三个
- observer处于Active
- observer.mLastVersion < livedata的mVersion
- 当前生命周期处于started或resumed下
- 注册的observer可与生命后期绑定,也可以是全局的,与生命周期绑定的observer会在destory后反注册
Lifecycle
- SupportActivity及其子类的生命周期是通过ReportFragment管理的,在onCreated是注入ReportFragment
- 非SupportActivity及其子类的,可以通过全局监听各个Activity的生命周期在onCreated是注入ReportFragment
- 非SupportActivity及其子类的生命周期管理是通过ProcessLifecycleOwner,ProcessLifecycleOwner在Activity onCreated时设置ReportFragment中监听来感知生命周期变化。可通过静态方法获取ProcessLifecycleOwner对象的LifecycleOwner实现对非SupportActivity及其子类的的感知。
- Lifecycle的状态分为DESTROYED、INITIALIZED、CREATED、STARTED、RESUMED 5种,在ViewModel中可以设置数据的是STARTED、RESUMED
技巧
- 通过注入Fragment来感知Activity的生命周期和一些Fragment以Activity绑定的一些方法,应用案例入ReportFragment、HolderFragment,另外权限管理和Activiyt跳转的返回值也可以通过这种方式
- 通过ContentProvider来初始化SDK,ContentProvider会在Application的attachContext之后,onCreate之前执行onCreate方法,在AndroidManifest.xml注册后,会自动初始化ContentProvider。但是如果需要对启动进行管理,或者sdk依赖于其他的sdk,则不适合通过ContentProvider来初始化SDK。