Android 架构组件之LiveData

Components之LiveData

LiveData解决了什么问题?

解决了在错综复杂的线程调度和生命周期中,View准确无误(合理生命周期)的更新,并且避免内存泄漏

observe(LifecycleOwner owner,Observer observer)

在LiveData实体类,利用observer来设置自定义观察者来通知界面的改变,并且传递一个LifecyclerOwner,那么LifeCyclerOwner是什么呢?

层层继承可以看到

看lifeCycler的三个要素

  • LifecyclerOwner
  • Lifecycle
  • LifecycleRegistry

LifecycleOwner

1
2
3
4
5
6
7
public interface LifecycleOwner {
/**
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}

只是一个接口,用于获取 Lifecycle

1
public class SupportActivity extends Activity implements LifecycleOwner

LifecycleRegistry

继承于Lifecycle是生命周期的分发类

Lifecycle

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

public abstract class Lifecycle {

@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);

@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);

@MainThread
public abstract State getCurrentState();

@SuppressWarnings("WeakerAccess")
public enum Event {

ON_CREATE,

ON_START,

ON_RESUME,

ON_PAUSE,

ON_STOP,

ON_DESTROY,

ON_ANY
}

@SuppressWarnings("WeakerAccess")
public enum State {

DESTROYED,

INITIALIZED,

CREATED,

STARTED,

RESUMED;

public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}

抽象类,LifecycleOwner接口中获取的就是它,可以看到用到观察者模式

说下LifecycleRegistry几个重要的方法

1
2
3
4
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}

我们先看一下使用的地方

1
2
3
4
observe(this@TestEasyActivity, Observer<List<CommonBean>> { t ->
Logger.d(GsonBuilder().setPrettyPrinting().create().toJson(t))
Logger.d("toto")
})

先从使用方面介绍,从知道LiveData中有一个observer方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}

只能创建一次,Owner只能拥有一个,也就是activity或者fragment

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 void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
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;
}

boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
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.
sync();
}
mAddingObserverCounter--;
}

在Registry中有一个mObserverMap
这个Map放入了一个Observer和一个Observerstatus,Observer是一个Key,ObserverStatus是为了通知Oberver的类

并且为了避免内存泄漏,这里用到了WeakReference,因为其持有Activity或者Fragment的引用

1
private final WeakReference<LifecycleOwner> mLifecycleOwner;

在add方法执行的时候会回调给Oberver一个Create的Event

movetostate

设置当前类的状态并且通知observer的方法

LifecycleObserver

没任何实现,只是一个接口,用于给观察者继承用的,但是官方定义了很多它的继承,用于不同的更新,比如像更新所有生命周期等等

那么LiveData用的是LifecycleBoundObserver
在它通知的方法里,明确的规定了再destory的时候移除掉Observer

1
2
3
4
5
6
7
8
9
public void onStateChanged(LifecycleOwner source, Lifecycle.Event ) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(observer);
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
}

并且在分Activity活动的时候,触发其中的ObserverNotify操作

SupprotActivity

1
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

那么Activity是怎么将生命周期回调给LifecycleRegistry的呢?

1
2
3
4
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}

1
2
3
4
5
6
7
8
9
10
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();
}
}

在里面添加了一个fragment,然后通过framgne的生命周期来通知

ProcessLifecycleOwnerInitializer

整个Application生命周期的回调除去oncreate和ondestory
它的初始化是继承contentProvider

1
2
3
4
5
6
7
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}

这个东西有头无尾,在整个项目中找不到这个类的调用

最终在Android的编译log中找到

1
2
3
4
5
6
7
8
9
10
provider#android.arch.lifecycle.ProcessLifecycleOwnerInitializer
ADDED from [android.arch.lifecycle:extensions:1.0.0] /Users/toto/.gradle/caches/transforms-1/files-1.1/extensions-1.0.0.aar/fbbf2d6a4e17302e3014153b1315b4f4/AndroidManifest.xml:25:9-29:43
android:authorities
ADDED from [android.arch.lifecycle:extensions:1.0.0] /Users/toto/.gradle/caches/transforms-1/files-1.1/extensions-1.0.0.aar/fbbf2d6a4e17302e3014153b1315b4f4/AndroidManifest.xml:27:13-68
android:multiprocess
ADDED from [android.arch.lifecycle:extensions:1.0.0] /Users/toto/.gradle/caches/transforms-1/files-1.1/extensions-1.0.0.aar/fbbf2d6a4e17302e3014153b1315b4f4/AndroidManifest.xml:29:13-40
android:exported
ADDED from [android.arch.lifecycle:extensions:1.0.0] /Users/toto/.gradle/caches/transforms-1/files-1.1/extensions-1.0.0.aar/fbbf2d6a4e17302e3014153b1315b4f4/AndroidManifest.xml:28:13-37
android:name
ADDED from [android.arch.lifecycle:extensions:1.0.0] /Users/toto/.gradle/caches/transforms-1/files-1.1/extensions-1.0.0.aar/fbbf2d6a4e17302e3014153b1315b4f4/AndroidManifest.xml:26:13-83

说明manifes被merge了
那么看看编译后的manifest,果然发现了

1
2
3
4
5
<provider
android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="com.example.android.codelabs.lifecycle.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />

最终通过shell在extensions-1.0.0包中发现

1
2
3
4
5
6
7
<application>
<provider
android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="${applicationId}.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
</application>

1
2
3
4
Application->attachBaseContext() 
ContentProvider->onCreate()
Application->onCreate()
Activity->onCreate()

Google的牛逼之处,隐身形初始化

1
2
3
4
5
6
7
8
9
private static AtomicBoolean sInitialized = new AtomicBoolean(false);

static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}

防止初始化的变量

1
2
3
4
5
6
7
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
ReportFragment.injectIfNeededIn(activity);
}

这里是注册了生命周期
ReportFragment.injectIfNeededIn(activity);

里面又做了什么事情呢?

1
2
3
4
5
6
7
8
9
10
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();
}
}

其实就是讲Fragment add到当前activity中
那么support的registerFragmentLifecycleCallbacks就有效果了

那么实际的分发在fragmnet中进行,为什么不在activity中进行呢?

因为并不是所有的Activity都是SupportActivity,那么就不会收到回调,那么自己的Activity继承了owner,并且自定义Register 注入了此fragment才会收到回调。所以除非自己实现lifecycler,否则就要用supprotactivity。

再看一下

so我们有了声明周期的时序图

1
2
3
4
5
6
7
8
9
10
11
sequenceDiagram
ProcessLifecycleOwnerInitializer -->>LifecycleDispatcher: init()
LifecycleDispatcher-->>DispatherActivityCallBack:new

DispatherActivityCallBack-->>ReportFragment:oncreateed inject
DispatherActivityCallBack-->>FragmentManager: registlifecycler
ReportFragment-->>DispatherActivityCallBack:ALL 声明周期
FragmentManager-->>DispatherActivityCallBack:oncreated,onstarted,onresumed
FragmentManager-->>DestructionReportFragment:add()
DestructionReportFragment-->>DispatherActivityCallBack: onpause,onstop,ondestory
DispatherActivityCallBack-->>LifecycleRegistry:Dispath status

再来看初始化中的另一个方法

1
2
3
4
5
6
7
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}

ProcessLifecycleOwner

ProcessLifecycleOwner的作用是整个application的生命周期回调,可以用来做一些事情,oncreate只会调用一次,ondestory永远不会被调用。通过此可以保证activity在recreated和destory或者configchange的时候不会不会分方法其他事件

LivingData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && existing.owner != wrapper.owner) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}

创建了一个LifecycleBoundObserver并且赛道了一个mObserver的map里面,这个map的主要作用就是为了在LiveData内部进行add 和 remove 操作。

1
private SafeIterableMap<Observer<T>, LifecycleBoundObserver> mObservers = new SafeIterableMap<>();

另外两个方法postvalue 和setValue其实是为在主线程和子线程更新value的操作,或者说是为了在并发的情况下去更新

1
2
3
4
5
6
7
8
9
10
11
12
private static final Object NOT_SET = new Object();
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}

1
2
3
4
5
6
7
8
9
10
11
12
private final Runnable mPostValueRunnable = new Runnable() {
@Override
public void run() {
Object newValue;
synchronized (mDataLock) {
newValue = mPendingData;
mPendingData = NOT_SET;
}
//noinspection unchecked
setValue((T) newValue);
}
};

可以借鉴一下,当并发多个操作执行时,只允许更新一次
那么setvalue会通知Observer去更新数据的改变.
那么怎么通知Observer呢?

1
2
3
4
5
6
7
8
9
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(observer);
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
}
1
2
3
static boolean isActiveState(State state) {
return state.isAtLeast(STARTED);
}

直接介绍lifecycler的时候告知了这些生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@SuppressWarnings("WeakerAccess")
public enum State {

DESTROYED,

INITIALIZED,

CREATED,

STARTED,

RESUMED;

public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}

开始介绍了lifecycler的流程,那么接下来看一下添加observer以及通知LiveData更新的流程

sequenceDiagram
    Activity-->>LiveData:observer
    LiveData-->LifecycleBoundObserver:new()
    LiveData-->>LifecycleRegistry:get()
    LifecycleRegistry-->>LifecycleBoundObserver:add()
    LifecycleRegistry-->>ObserverWithState:new()
    LifecycleRegistry-->>ObserverWithState:addObserver()
    ObserverWithState-->>LifecycleRegistry:dispath()
    DispatherActivityCallBack-->>LifecycleRegistry:handleLifecycleEvent()
    LifecycleRegistry-->>LifecycleBoundObserver:onStateChanged()
    LifecycleBoundObserver-->>LiveData:dispatchingValue()
    LiveData-->>Activity:observer.onChanged((T) mData);
自己通知自己的流程
sequenceDiagram
    Activity-->>LiveData:observer
    LifecycleBoundObserver-->>LiveData:new
    LiveData->>LifecycleRegistry:LifecycleBoundObserver->in
    LiveData-->>LifecycleRegistry:get()
    ObserverWithState-->>LifecycleRegistry:new()
    LifecycleRegistry->>ObserverWithState:LifecycleBoundObserver->in
    LifecycleRegistry-->>ObserverWithState:dispatchEvent()
    ObserverWithState-->>LifecycleBoundObserver:LifecycleBoundObserver.onStateChanged()
    LifecycleBoundObserver-->>LifecycleBoundObserver:activeStateChanged()
    LifecycleBoundObserver-->>LiveData:dispatchingValue(LifecycleBoundObserver)
    LiveData-->>LiveData:considerNotify(LifecycleBoundObserver)
    LiveData-->>Activity:onChanged((T) mData);

//只要mutableLivedata的index不是初始值-1那么就会通知!

MutableLiveData.addSource()方法中插入LiveData的值不是-1,
那么就会调用onchange方法

谢谢您的鼓励~