美文网首页Android开发技能知识点Android进阶之旅Android知识
RxBus告诉你:Android应用如何完全退出“最优雅”

RxBus告诉你:Android应用如何完全退出“最优雅”

作者: Adam289 | 来源:发表于2017-05-05 10:07 被阅读682次

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));//发送退出指令

大功告成!

相关文章

网友评论

  • 路人可乙:还是放ActivityLifecycle里面吧 这样第三方的activity也可以关闭了
  • 炎之铠:作者能给一下你的RxBus的实现代码吗?RxJava新手有点东西不是很懂,想了解一下
    Adam289:可以,RxBus是这样的:
    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);
    }
    }

本文标题:RxBus告诉你:Android应用如何完全退出“最优雅”

本文链接:https://www.haomeiwen.com/subject/swujtxtx.html