Android中的rxbus简单封装
/**
* Created by Zhuyuanqiang on 2018/9/26.
*/
public class RxBus {
private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
private final Map<String, Object> tags = new HashMap<>(); //post队列
private final Map<String, Object> sendtags = new HashMap<>(); //结果发送队列
private static RxBus rxbus;
public static RxBus getInstance() {
if (rxbus == null) {
synchronized (RxBus.class) {
if (rxbus == null) {
rxbus = new RxBus();
}
}
}
return rxbus;
}
/**
* 发送事件消息
* @param tag 用于区分事件
* @param object 事件的参数
*/
public void post(String tag, Object object) {
if (!tags.containsKey(tag)) {
tags.put(tag, object);
_bus.onNext(object);
sendtags.put(tag, object);
} else {
tags.remove(tag);
tags.put(tag, object);
_bus.onNext(object);
sendtags.put(tag, object);
}
}
/**
* 主线程中执行
*/
public void toObserverableOnMainThread(final String tag, final RxBusResult rxBusResult) {
_bus.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
@Override
public void call(Object o) {
if (sendtags.containsKey(tag)) {
rxBusResult.onRxBusResult(sendtags.get(tag));
//sendtags.remove(tag);
}
}
});
}
/**
* 子线程中执行
*/
public void toObserverableChildThread(final String tag, final RxBusResult rxBusResult) {
_bus.observeOn(Schedulers.io()).subscribe(new Action1<Object>() {
@Override
public void call(Object o) {
if (sendtags.containsKey(tag)) {
rxBusResult.onRxBusResult(sendtags.get(tag));
//sendtags.remove(tag);
}
}
});
}
/**
* 移除tag
*/
public void removeObserverable(String tag) {
if (tags.containsKey(tag)) {
tags.remove(tag);
}
if (sendtags.containsKey(tag)) {
sendtags.remove(tag);
}
}
/**
* 退出应用时,清空资源
*/
public void release() {
tags.clear();
sendtags.clear();
rxbus = null;
}
}
在需要传递消息时调用
rxBus.post(RequestType.PRINT, new String(dataPool.datapool(RequestType.PRINT, content)));
在接收时的回调响应处理
rxBus.toObserverableOnMainThread(RequestType.PRINT, new RxBusResult() {
public void onRxBusResult(Object o) {
String msg = (String) o;
Log.i("======msg:", msg);
requestAidl(msg);
}
});
这就完成了一个简单组件之间通信的应用场景, 有木有很简单!