半天学会RxBus的简单使用

2018-06-12  本文已影响0人  reaiya

参考文章:https://blog.csdn.net/senkai123/article/details/78202217

1. 准备

依赖rxrelay2使RxBus具备异常处理能力

compile 'com.jakewharton.rxrelay2:rxrelay:2.0.0'

实现RxBus

public class RxBus {
    private static volatile RxBus instance;
    private final Relay<Object> mBus;

    public RxBus() {
        this.mBus = PublishRelay.create().toSerialized();
    }

    public static RxBus getInstance() {
        if (instance == null) {
            synchronized (RxBus.class) {
                if (instance == null) {
                    instance = Holder.BUS;
                }
            }
        }
        return instance;
    }
    public void post(Object obj) {
        mBus.accept(obj);
    }

    public <T> Observable<T> toObservable(Class<T> tClass) {
        return  mBus.ofType(tClass);
    }

    public Observable<Object> toObservable() {
        return mBus;
    }

    public boolean hasObservers() {
        return mBus.hasObservers();
    }

    private static class Holder {
        private static final RxBus BUS = new RxBus();
    }
}

2. 使用

注册被观察者

    RxBus.getInstance().toObservable().map(new Function<Object, EventMsg<String>>() {
            @Override
            public EventMsg<String> apply(@NonNull Object o) throws Exception {
                return (EventMsg<String>) o;
            }
        }).subscribe(new Consumer<EventMsg<String>>() {
            @Override
            public void accept(EventMsg<String> stringEventMsg) throws Exception {
                if (null != stringEventMsg) {
                    mainText1.setText(stringEventMsg.getMsg().toString());
                }
            }
        });

观察者发送消息

    EventMsg<String> eventMsg = new EventMsg<>();
    eventMsg.setCode(200);
    eventMsg.setMsg("这是第二页传来的消息");
    RxBus.getInstance().post(eventMsg);

消息实体

public class EventMsg<T> {
    private int code;
    private T msg;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getMsg() {
        return msg;
    }

    public void setMsg(T msg) {
        this.msg = msg;
    }
}

写于2018-4-5

上一篇下一篇

猜你喜欢

热点阅读