RxBus
public class RxBus {
private final Subject<Object, Object> _bus;
private RxBus() {
_bus = new SerializedSubject<>(PublishSubject.create());
}
public static synchronized RxBus getInstance() {
return RxBusHolder.instance;
}
public void post(Object o) {
_bus.onNext(o);
}
public <T> Observable<T> toObserverable(Class<T> eventType) {
return _bus.ofType(eventType);
}
private static class RxBusHolder {
private static final RxBus instance = new RxBus();
}
}
这里使用静态内部类的方式实现单例模式
使用也非常的简单,在发送消息的地方,例如
RxBus.getInstance().post("logout");
在接收消息的地方,例如
MainActivity{
private Subscription subscription;
//这里省略onCreate方法
private void init(){
subscription = RxBus.getInstance().toObserverable(String.class).subscribe(new Action1<String>() {
@Override
public void call(String s) {
if ("logout".equals(s)) {
finish();
}
}
});
}
}
记得在适当的地方销毁,例如
@Override
protected void onDestroy() {
super.onDestroy();
subscription.unsubscribe();
}