RxBus告诉你:Android应用如何完全退出“最优雅”
首先,在基类BaseActivity里,注册RxBus监听:
public class BaseActivity extends AppCompatActivity {
Subscription mSubscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.intiSySBar(this, R.color.colorblack);
initRxBus();
}
//接收退出的指令,关闭所有activity
private void initRxBus() {
mSubscription = RxBus.getInstance().toObserverable(NormalEvent.class)
.subscribe(new Action1<NormalEvent>() {
@Override
public void call(NormalEvent userEvent) {
if (userEvent.getType() == -1) {
finish();
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (!mSubscription.isUnsubscribed()) {
mSubscription.unsubscribe();
}
}
}
这是事件实体NormalEvent:
public class NormalEvent {
private int type;
public NormalEvent(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
最后,在需要退出的地方调用:
RxBus.getInstance().post(new NormalEvent(-1));//发送退出指令
大功告成!
网友评论
public class RxBus {
private final Subject<Object, Object> _bus;
private static class RxBusHolder {
private static final RxBus instance = new RxBus();
}
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);
}
}