最近使用Rxbus发现升级到33版本的时候,会出现报黄色,看着很不舒服。然后就想着找找替换的方案。查找了蛮多资料。发现版本大部分都是大同小异。就如下的链接的三个版本。第一个就是简单实现类型。也是之前Rxbus早期的原型。再就是后面我用来改良的版本。
但是跟之前用的Rxbus又有点不一样。因为原先都是习惯了的懒人写法。所以就用当前的类名(XXX.getClass().getSimpleName())来替代需要一直定义的订阅键值。好吧,话不多说。直接上源码:
/**
* LiveDataBus 数据交互帮助类
*
* <p>
* Created by
* Change
*/
public class LiveDataBus {
public static final Map<String, BusMutableLiveData<Object>> bus = new HashMap<>();
public static synchronized <T> MutableLiveData<T> toObservable(Class<T> type){
String key = type.getSimpleName();
if (!bus.containsKey(key)){
bus.put(key, new BusMutableLiveData<>());
}
return (MutableLiveData<T>) bus.get(key);
}
public static void post(Object type){
String key = type.getClass().getSimpleName();
if (!bus.containsKey(key)){
bus.put(key, new BusMutableLiveData<>());
}
Objects.requireNonNull(bus.get(key)).postValue(type);
}
private static class ObserverWrapper<T> implements Observer<T> {
private Observer<T> observer;
public ObserverWrapper(Observer<T> observer) {
this.observer = observer;
}
@Override
public void onChanged(@Nullable T t) {
if (observer != null) {
if (isCallOnObserve()) {
return;
}
observer.onChanged(t);
}