5.LiveData

注意:一般情况下,LiveData要配合ViewModel一起使用的

但是本文章是单独使用 LiveData作为学习,这样的话,我们就可以只关注LiveData了

组件通信常见的几种方式

Intent

Interface(接口在第三方框架用的最多)

aidl(难 跨进程通信)

Handler(单组件)

BroadCast

第三方组件通信框架(EventBus…)

做组件通信 官方是推荐使用LiveData的

LiveData是什么?

充当两个角色,既有观察者,又有被观察者

LiveData是一种可观察数据存储器类。与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。 这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。

数据驱动UI

LiveData是一个数据持有类

能够感知组件的生命周期

持有的数据可以被观察者观察

观察者:接口

在LiveData里面,是可以持有很多很多的观察者

LifecycleBoundObserver -> ObserverWrapper(对观察者的封装)

1
2
3
4
5
6
7
8
9
10
11
12
//在LiveData的observe(owner,observer)方法里面
private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers =
new SafeIterableMap<>();


LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
//将观察者 and LifecycleBoundObserver 存储在Map里面
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);

//注册生命周期的观察者
owner.getLifecycle().addObserver(wrapper);

生命周期方法会回调多次,接口Observer观察者这会回调一次?(通过版本号判断的)

postValue可以在任意线程下被调用(会有一个切换到主线程的操作)

setValue只能在主线程中被调用

面试

观察者跟接口有什么区别?

观察者就是接口

区别:所处的位置,用来干嘛

接口是一对一的关系(一个接口对应一个请求)这个接口只会观察一个地方,只会被某一个地方回调,是一对一的关系

观察者是一对多的关系

观察者是同时有很多的接口去观察某一个地方

1
2
3
4
5
6
7
public interface Observer<T> {
/**
* Called when the data is changed.
* @param t The new data
*/
void onChanged(T t);
}

LiveData 是如何避免内存泄漏的?

  • LiveData 的数据观察者通常是匿名内部类,它持有界面的引用,可能造成内存泄漏。
  • LiveData 内部会将数据观察者进行封装,使其具备生命周期感知能力。当生命周期状态为 DESTROYED 时,自动移除观察者

在 LiveData 内部 Observer 会被包装成LifecycleBoundObserver,其实现了LifecycleEventObserver接口,重写其onStateChanged()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
// 若生命周期为 DESTROYED 则移除数据观察者并返回
if (currentState == DESTROYED) {
removeObserver(mObserver);
return;
}
Lifecycle.State prevState = null;
while (prevState != currentState) {
prevState = currentState;
activeStateChanged(shouldBeActive());
currentState = mOwner.getLifecycle().getCurrentState();
}
}

LiveData 是什么?

阿里Android三面真题,想进阿里关于LiveData的这三个问题你至少得答出来_android livedata的坑-CSDN博客

LiveData 为什么被设计出来,解决了什么问题?

说说LiveData原理。

LiveData 用过吧?setValue()posValue()有啥区别?原理是啥?

Jetpack-LiveData(面试深度起来)_livedata面试题-CSDN博客

observe()observeForever()知道么? 原理是啥,数据是怎么分发的?

LiveData 黏性知道怎么肥事吗?原理是啥?怎么解决?

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信