LiveData升级版
前言
系统的Livedata由于内部使用ObserverWrapper封装Observer,通过粘性效果实现通知,有些时候不需要粘性通知,需要在订阅之后再观察事件,通过反射修改如下:
public class BusMutableLiveData extends MutableLiveData {@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer super T> observer) {
super.observe(owner, observer);
hook(observer);
}private void hook(Observer super T> observer) {
Class liveDataClass = LiveData.class;
try {
//获取field private SafeIterableMap, ObserverWrapper> mObservers
Field mObservers = liveDataClass.getDeclaredField("mObservers");
mObservers.setAccessible(true);
//获取SafeIterableMap集合mObservers
Object observers = mObservers.get(this);
Class> observersClass = observers.getClass();
//获取SafeIterableMap的get(Object obj)方法
Method methodGet = observersClass.getDeclaredMethod("get", Object.class);
methodGet.setAccessible(true);
//获取到observer在集合中对应的ObserverWrapper对象
Object objectWrapperEntry = methodGet.invoke(observers, observer);
Object objectWrapper = null;
if (objectWrapperEntry instanceof Map.Entry) {
objectWrapper = ((Map.Entry) objectWrapperEntry).getValue();
}
if (objectWrapper == null) {
throw new NullPointerException("ObserverWrapper can not be null");
}
//获取ObserverWrapper的Class对象LifecycleBoundObserver extends ObserverWrapper
Class> wrapperClass = objectWrapper.getClass().getSuperclass();
//获取ObserverWrapper的field mLastVersion
Field mLastVersion = wrapperClass.getDeclaredField("mLastVersion");
mLastVersion.setAccessible(true);
//获取liveData的field mVersion
Field mVersion = liveDataClass.getDeclaredField("mVersion");
mVersion.setAccessible(true);
Object mV = mVersion.get(this);
//把当前ListData的mVersion赋值给 ObserverWrapper的field mLastVersion
mLastVersion.set(objectWrapper, mV);
mObservers.setAccessible(false);
methodGet.setAccessible(false);
mLastVersion.setAccessible(false);
mVersion.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
封装
【LiveData升级版】上面试Livedata的封装,平时使用的情况下简化过程,封装工具类如下:
public class LiveDataBus {private final Map> mBus;
private LiveDataBus() {
mBus = new ArrayMap<>();
}private static abstract class SingleHolder {
private static final LiveDataBus DATA_BUS = new LiveDataBus();
}public static LiveDataBus get() {
return SingleHolder.DATA_BUS;
}/**
* 订阅事件
*
* @param event
*/
public void subscribe(T event) {
if (null == event) {
throw new IllegalArgumentException("Subscribed events must be not null!");
}String eventName = event.getClass().getName();
if (!mBus.containsKey(eventName)) {
mBus.put(eventName, new BusMutableLiveData<>());
}BusMutableLiveData liveData = https://www.it610.com/article/mBus.get(eventName);
if (null != liveData) {
liveData.setValue(event);
}
}/**
* 观察事件
*
* @param eventType
* @return
*/
public T observable(Class eventType) {
String eventName = eventType.getName();
if (TextUtils.isEmpty(eventName)) {
throw new IllegalArgumentException("Observered events must be not null!");
}
return mBus.get(eventName).getValue();
}/**
* 观察事件
*
* @param eventType
* @return
*/
public LiveData postObservable(Class eventType) {
String eventName = eventType.getName();
if (TextUtils.isEmpty(eventName)) {
throw new IllegalArgumentException("Observered events must be not null!");
}
BusMutableLiveData tBusMutableLiveData = https://www.it610.com/article/mBus.get(eventName);
if(tBusMutableLiveData==null) {
throw new IllegalArgumentException("The event you observe has not been subscribed!");
}
return mBus.get(eventName);
}}
第二种
public class LifecycleBus {private MutableLiveData liveData;
public final static boolean MODE_SYSTEM = false;
private LifecycleBus() {
}private static abstract class SingleHolder {
private static final LifecycleBus DATA_BUS = new LifecycleBus();
}public static LifecycleBus get() {
return LifecycleBus.SingleHolder.DATA_BUS;
}/**
* 订阅事件
*
* @param event
*/
protected void subscribe(T event) {
subscribe(MODE_SYSTEM,event);
}/**
* 订阅事件
*
* @param event
*/
protected void subscribe(boolean useSystem,T event) {
if (null == event) {
throw new IllegalArgumentException("Subscribed events must be not null!");
}
liveData = https://www.it610.com/article/useSystem ? new MutableLiveData() : new LifecycleLiveData();
liveData.setValue(event);
}/**
* 观察事件
*
* @param activity
* @param observer
*/
public void observe(@NonNull AppCompatActivity activity, @NonNull Observer super T> observer) {
if (liveData =https://www.it610.com/article/= null) {
throw new IllegalArgumentException("The event you observe has not been subscribed!");
}
if (liveData instanceof LifecycleLiveData) {
LifecycleLiveData lifecycleLiveData = https://www.it610.com/article/(LifecycleLiveData) liveData;
lifecycleLiveData.observe(activity, observer);
} else {
liveData.observe(activity, observer);
}
}/**
* 观察事件
*
* @param fragment
* @param observer
*/
public void observe(@NonNull Fragment fragment, @NonNull Observer super T> observer) {
if (liveData =https://www.it610.com/article/= null) {
throw new IllegalArgumentException("The event you observe has not been subscribed!");
}
if (liveData instanceof LifecycleLiveData) {
LifecycleLiveData lifecycleLiveData = https://www.it610.com/article/(LifecycleLiveData) liveData;
lifecycleLiveData.observe(fragment, observer);
} else {
liveData.observe(fragment, observer);
}
}/**
* 内部类继承
* MutableLiveData
*
* @param
*/
public class LifecycleLiveData extends MutableLiveData {private final HashMap observers = new HashMap<>();
public void observe(@NonNull AppCompatActivity activity, @NonNull Observer super T> observer) {
LifecycleOwner owner = activity;
Integer storeId = System.identityHashCode(activity.getViewModelStore());
observe(storeId, owner, observer);
}public void observe(@NonNull Fragment fragment, @NonNull Observer super T> observer) {
LifecycleOwner owner = fragment.getViewLifecycleOwner();
Integer storeId = System.identityHashCode(fragment.getViewModelStore());
observe(storeId, owner, observer);
}private void observe(@NonNull Integer storeId, @NonNull LifecycleOwner owner, @NonNull Observer super T> observer) {
if (observers.get(storeId) == null) {
observers.put(storeId, true);
}
super.observe(owner, t -> {
if (!observers.get(storeId)) {
observers.put(storeId, true);
}
if (t != null) {
observer.onChanged(t);
}
});
}/**
* 禁用此方法
*
* @param observer
*/
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer super T> observer) {
}/**
* 禁用此方法
*
* @param observer
*/
@Override
public void observeForever(@NonNull Observer super T> observer) {
}@Override
public void setValue(T value) {
if (value != null) {
for (Map.Entry entry : observers.entrySet()) {
entry.setValue(false);
}
super.setValue(value);
}
}/**
* 清理
*/
public void clear() {
super.setValue(null);
}
}}
推荐阅读
- 由浅入深理解AOP
- android|android studio中ndk的使用
- 斐讯K2|斐讯K2 固件搜集
- 植物能治病的奥秘——植物精气
- 11-代码注入
- linux定时任务contab
- neo4j|neo4j cql语句 快速查询手册
- 构建App(一)(框架与结构)
- 从如何使用到如何实现一个Promise
- C#中类的异常处理详解