架构组件

问题

  • 如何做到activity转屏时,保存数据
  • LiveData如何做到感知生命周期,如何在生命周期完全结束时,销毁数据

ViewModel

1
2
3
4
5
6
7
8
9
10
11
12
13
 public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
this.mViewModelStore = store;
}

public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
Application application = checkApplication(activity);
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(ViewModelStores.of(activity), factory);
}

ViewModelStore为ViewModelStores.of(activity)

1
2
3
4
5
6
public static ViewModelStore of(@NonNull FragmentActivity activity) {
if (activity instanceof ViewModelStoreOwner) {
return ((ViewModelStoreOwner) activity).getViewModelStore();
}
return holderFragmentFor(activity).getViewModelStore();
}

在FragmentActivity中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@NonNull
public ViewModelStore getViewModelStore() {
if (this.getApplication() == null) {
throw new IllegalStateException("Your activity is not yet attached to the Application instance. You can't request ViewModel before onCreate call.");
} else {
if (this.mViewModelStore == null) {
FragmentActivity.NonConfigurationInstances nc = (FragmentActivity.NonConfigurationInstances)this.getLastNonConfigurationInstance();
if (nc != null) {
this.mViewModelStore = nc.viewModelStore;
}

if (this.mViewModelStore == null) {
this.mViewModelStore = new ViewModelStore();
}
}

return this.mViewModelStore;
}
}

FragmentActivity.NonConfigurationInstances代码

1
2
3
4
5
6
7
8
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
FragmentManagerNonConfig fragments;

NonConfigurationInstances() {
}
}

可以看到保存了ViewModelStore,而系统在onRetainNonConfigurationInstance()中保存了该对象

1
2
3
4
5
6
7
8
9
10
11
12
13
public final Object onRetainNonConfigurationInstance() {
Object custom = this.onRetainCustomNonConfigurationInstance();
FragmentManagerNonConfig fragments = this.mFragments.retainNestedNonConfig();
if (fragments == null && this.mViewModelStore == null && custom == null) {
return null;
} else {
FragmentActivity.NonConfigurationInstances nci = new FragmentActivity.NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = this.mViewModelStore;
nci.fragments = fragments;
return nci;
}
}

onRetainNonConfigurationInstance()功能与onSaveInstanceState()类似,同样是用于在转屏时保存数据状态,不同的是前者可以返回一个包含有状态信息的Object,其中甚至可以包含Activity Instance本身。新创建的Activity可以继承大量来自于Parent Activity State信息。

最后在destory中clean,并且不是转屏才进行clean操作

1
2
3
4
5
6
7
8
protected void onDestroy() {
super.onDestroy();
if (this.mViewModelStore != null && !this.isChangingConfigurations()) {
this.mViewModelStore.clear();
}

this.mFragments.dispatchDestroy();
}

LiveData

添加观察者

1
2
3
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {}

public void observeForever(@NonNull Observer<T> observer) {}

Android提供了两种添加观察者的方式

第一种根据提供的LifecycleOwner来进行状态的监听,也就是shouldBeActive

1
2
3
4
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}

他的默认实现LifecycleObserver的类为LifecycleBoundObserver

而第二种方式,实现类为AlwaysActiveObserver,他的方法为

1
2
3
4
@Override
boolean shouldBeActive() {
return true;
}

所以如果你使用第二种方式,你需要自己去调用removeObserver(Observer)来销毁LiveData的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
//Observer的包装模式
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
//有wrapper就返回,没有就添加
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
//如果map中已经有了ObserverWrapper则不进行add
if (existing != null) {
return;
}
//这一步后面,其实就是Lifecycle的源码部分了
owner.getLifecycle().addObserver(wrapper);
}

Lifecycle

26.1.0以上的版本中,Fragments和Activities 实现了Lifecyclel的类为LifecycleRegistry

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
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//一个简单的封装类
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//有ObserverWithState就返回,没有就添加
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
//mAddingObserverCounter 统计添加的observer个数
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
//分发事件,调用 mLifecycleObserver.onStateChanged(owner, event)
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}

if (!isReentrance) {
// we do sync only on the top level.
//进行同步,最终同样调用到onStateChanged
sync();
}
mAddingObserverCounter--;
}

监听回调

LifecycleBoundObserver源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {

......

@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}

@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}

......
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void activeStateChanged(boolean newActive) {
if (newActive == mActive) {
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
boolean wasInactive = LiveData.this.mActiveCount == 0;
LiveData.this.mActiveCount += mActive ? 1 : -1;
if (wasInactive && mActive) {
onActive();
}
if (LiveData.this.mActiveCount == 0 && !mActive) {
onInactive();
}
if (mActive) {
dispatchingValue(this);
}
}

dispatchingValue方法中会调用considerNotify

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {
return;
}
//这里判断了观察者的状态,其实也就是LifecycleOwner的状态
//return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
//将值进行回调给Observer
observer.mObserver.onChanged((T) mData);
}

感知生命周期的工作,由Lifecycle组件完成

默认的Fragment中,会调用LifecycleRegistry的handleLifecycleEvent

比如

1
2
3
4
5
6
7
8
void performPause() {
if (this.mView != null) {
this.mViewLifecycleRegistry.handleLifecycleEvent(Event.ON_PAUSE);
}

this.mLifecycleRegistry.handleLifecycleEvent(Event.ON_PAUSE);
......
}
  • handleLifecycleEvent()
  • moveToState()
  • sync()
  • backwardPass()/forwardPass()
  • observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState))
  • mLifecycleObserver.onStateChanged(owner, event)

而在Activity中,则是通过创建无UI的Fragment来分发这些状态

1
2
3
4
5
6
7
8
9
10
11
12
public class SupportActivity extends Activity implements LifecycleOwner {
...

@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}

...
}

ReportFragment:

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
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}

...

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}

@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
...
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}

if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}

可以看到,最终会回调到handleLifecycleEvent

因此,当你使用Lifecycler时,要注意一点,Lifecycler的回调都是在你编写代码的后面

1
2
3
4
5
@Override
protected void onResume() {
super.onResume();
//之后会回调Lifecycler中的事件
}