使用RxBus替换EvenBus

来源:互联网 发布:阿里云怎么绑定域名 编辑:程序博客网 时间:2024/06/07 22:42
//在android studio中导入rxjava的jar包,我本人用的是当前版本的
compile 'io.reactivex:rxjava:1.3.0'compile 'io.reactivex:rxandroid:1.2.1'
然后新建一个工具类,RxBus
 
import android.util.Log;import rx.Observable;import rx.android.schedulers.AndroidSchedulers;import rx.schedulers.Schedulers;import rx.subjects.PublishSubject;import rx.subjects.SerializedSubject;import rx.subjects.Subject;public class RxBus {    private final Subject<Object, Object> bus;    private static volatile RxBus inst;    private RxBus() {        bus = new SerializedSubject<>(PublishSubject.create());    }    public static RxBus getInst() {        if (inst == null) {            synchronized (RxBus.class) {                if (inst == null)                    inst = new RxBus();            }        }        return inst;    }
//这里类似于通知,设置一个tag,在接收端可以根据tag接收进行操作    public void post(String tag) {        post(tag, null);    }    /**     * 发送     * @param tag  通知tag,便于判断     * @param obj    用于传递的Object 对象     */    public void post(String tag, Object obj) {        Log.e("RxBus", "post tag:" + tag);        post(new RxEvent(tag, obj));    }    private void post(RxEvent rxEvent) {        bus.onNext(rxEvent);    }    /**     * io线程接收     * @return     */    public Observable<RxEvent> toObserveOnIO() {        return bus.observeOn(Schedulers.io()).ofType(RxEvent.class);    }    /**     * 主线程接收     * @return     */    public Observable<RxEvent> toObserveOnMain() {        return bus.observeOn(AndroidSchedulers.mainThread()).ofType(RxEvent.class);    }
//这里是共用的bean实例化
public class RxEvent {    /**     * 用来区分消息类型     */    public String tag;    /**     * 参数     */    public Object obj;    public RxEvent() {    }    public RxEvent(String tag, Object obj) {        this.tag = tag;        this.obj = obj;    }    @Override    public String toString() {        return "RxEvent{" +                "tag='" + tag + '\'' +                ", obj=" + obj +                '}';    }}

然后在其他地方进行注册调用,可以任意地方,tag是标识,可以是任意数
String tag1="没传对象";int tag2="有传对象bean";
//传递你要用到的bean.这里比如studentStudent student=new Stduent();
RxBus.getInst().post(tag1);//注册简单通知的对象;
RxBus.getInst().post(tag2,student);//注册传递对象的通知对象;

注册完通知对象后,可以在我们要收到通知的地方进行接收通知;
mSubscription = RxBus.getInst()        .toObserveOnMain()        .subscribe(new Action1<RxEvent>() {            @Override            public void call(RxEvent rxEvent) {                             switch (rxEvent.tag) {                                      case "没传对象": //这里接收到简单通知,可以在主线程上进行任意操作                                             break;                    case "有传对象的bean":                        doSomething((Student) rxEvent.obj);//在RxEvent中获取object,强转为我要刚传递的对象;                        break;                               }            }        });

  @Override   public void onStop() {    super.onStop();    //结束对象通知    if (mSubscription != null && !mSubscription.isUnsubscribed())        mSubscription.unsubscribe();}
}
原创粉丝点击