基于Rxrelay的RxBus

一、概述:过去项目之间传值除了用intent之外用的eventbus比较多,但是最新的项目我是用RxJava+retrofit+mvp搭建的,因为使用了rxjava所以可以直接封装rxbus而无需添加eventbus的依赖。

  1、Rxrelay:既是一个Observable 也是 一个Consumer的RxJava。使用它的好处就是不必担心事件在onComplete或者onError后终止事件订阅关系,它允许将非Rx API连接到Rx,而不用担心意外触发终端状态(onComplete或者onError)。

  2、Rxrelay:有3个子类:

  • BehaviorRelay:他会接收订阅之前的最后一个事件和订阅之后的事件。
  • PublishRelay:只接受订阅后的事件。
  • ReplayRelay:接受订阅前和订阅后的所有事件。

  3.Rxrelay源码:点击打开链接

二、RxBus代码

  1、演示效果:

 基于Rxrelay的RxBus_第1张图片

  2、添加依赖: 

//rxJava
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.5'
//RxRelay
compile 'com.jakewharton.rxrelay2:rxrelay:2.0.0'
  3、核心代码:

public class RxBus {

  private Relay<Object> rxBus = null;

  private static RxBus instance;

  private static class IRxBusHolder {
    private static final RxBus INSTANCE = new RxBus();
  }

  private RxBus() {
    rxBus = BehaviorRelay.create().toSerialized();
  }

  public static final RxBus getInstance() {
    return IRxBusHolder.INSTANCE;
  }

  public void post(Object event) {
    rxBus.accept(event);
  }

  private <T> Observable<T> register(Class<T> eventType) {
    return rxBus.ofType(eventType);
  }

  public <T> Disposable toObservable(Class<T> eventType, Consumer<T> onNext) {
    return register(eventType)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(onNext);
  }

  public <T> Disposable toObservable(
      Class<T> eventType, Scheduler subScheduler, Scheduler obsScheduler, Consumer<T> onNext) {
    return register(eventType).subscribeOn(subScheduler).observeOn(obsScheduler).subscribe(onNext);
  }

  public <T> Disposable toObservable(Class<T> eventType, Consumer<T> onNext, Consumer onError) {
    return register(eventType)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(onNext, onError);
  }

  public <T> Disposable toObservable(
      Class<T> eventType,
      Scheduler subScheduler,
      Scheduler obsScheduler,
      Consumer<T> onNext,
      Consumer onError) {
    return register(eventType)
        .subscribeOn(subScheduler)
        .observeOn(obsScheduler)
        .subscribe(onNext, onError);
  }

  public <T> Disposable toObservable(
      Class<T> eventType, Consumer<T> onNext, Consumer onError, Action onComplete) {
    return register(eventType)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(onNext, onError, onComplete);
  }

  public <T> Disposable toObservable(
      Class<T> eventType,
      Scheduler subScheduler,
      Scheduler obsScheduler,
      Consumer<T> onNext,
      Consumer onError,
      Action onComplete) {
    return register(eventType)
        .subscribeOn(subScheduler)
        .observeOn(obsScheduler)
        .subscribe(onNext, onError, onComplete);
  }

  public <T> Disposable toObservable(
      Class<T> eventType,
      Consumer<T> onNext,
      Consumer onError,
      Action onComplete,
      Consumer onSubscribe) {
    return register(eventType)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(onNext, onError, onComplete, onSubscribe);
  }

  public <T> Disposable toObservable(
      Class<T> eventType,
      Scheduler subScheduler,
      Scheduler obsScheduler,
      Consumer<T> onNext,
      Consumer onError,
      Action onComplete,
      Consumer onSubscribe) {
    return register(eventType)
        .subscribeOn(subScheduler)
        .observeOn(obsScheduler)
        .subscribe(onNext, onError, onComplete, onSubscribe);
  }

  public boolean isObserver() {
    return rxBus.hasObservers();
  }

  public void unregister(Disposable disposable) {
    if (disposable != null && !disposable.isDisposed()) {
      disposable.dispose();
    }
  }
}
  4、自定义事件类型:

public class EventMsg<T> {

  private T event;
  
  private List list;
  
  private String tag;

  public EventMsg(T event) {
    this.event = event;
  }

  public EventMsg(String tag, T event) {
    this.tag = tag;
    this.event = event;
  }

  public EventMsg(List list) {
    this.list = list;
  }

  public EventMsg(String tag, List list) {
    this.tag = tag;
    this.list = list;
  }

  public String getTag() {
    return tag;
  }

  public T getData() {
    return event;
  }

  public List getList() {
    return list;
  }
}

  5、调用:

public class FirstActivity extends AppCompatActivity {

  private Disposable disposable;
  private TextView nextTv;
  private Button nextBtn;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
    nextTv = findViewById(R.id.tv_next);
    nextBtn = findViewById(R.id.btn_next);

    RxBus.getInstance()
        .toObservable(
            EventMsg.class,
            AndroidSchedulers.mainThread(),
            AndroidSchedulers.mainThread(),
            new Consumer<EventMsg>() {
              @Override
              public void accept(EventMsg eventMsg) throws Exception {
                if (Constant.OFF.equals(eventMsg.getTag())) {
                  nextTv.setText(eventMsg.getData() + "");
                }
              }
            });

    nextBtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            RxBus.getInstance().post(new EventMsg<String>(Constant.ON, "来自FirstActivity的消息!"));
            startActivity(new Intent(FirstActivity.this, SecondActivity.class));
          }
        });
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (RxBus.getInstance().isObserver()) {
      RxBus.getInstance().unregister(disposable);
    }
  }
}

public class SecondActivity extends AppCompatActivity {

  private Disposable disposable;
  private TextView testTv;
  private Button nextBtn;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    testTv = findViewById(R.id.tv_test);
    nextBtn = findViewById(R.id.btn_next);

    disposable =
        RxBus.getInstance()
            .toObservable(
                EventMsg.class,
                new Consumer<EventMsg>() {
                  @Override
                  public void accept(EventMsg eventMsg) throws Exception {
                    if (Constant.ON.equals(eventMsg.getTag())) {
                      testTv.setText(eventMsg.getData() + "");
                    }
                  }
                });

    nextBtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            RxBus.getInstance().post(new EventMsg<String>(Constant.OFF, "来自SecondActivity的消息!"));
            finish();
          }
        });
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (RxBus.getInstance().isObserver()) {
      RxBus.getInstance().unregister(disposable);
    }
  }
}

三、源码地址:点击打开链接


你可能感兴趣的:(安卓)