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();
}