android之使用RxJava实现EventBus事件总线

1.引入依赖

//rxjava
implementation 'io.reactivex.rxjava2:rxjava:2.1.7'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

2.RxBus代码

/**
 * 用RxJava实现EventBus
 */
public class RxBus {
    private static RxBus instance;
    private ConcurrentHashMap> subjectMapper=new ConcurrentHashMap<>();

    public static synchronized RxBus getInstance(){
        if (instance==null){
            instance=new RxBus();
        }
        return instance;
    }

    private RxBus(){}

    /**
     * 订阅事件源
     */
    public RxBus onEvent(Observable mObservable, Consumer mAction1){
        mObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(mAction1, new Consumer() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        });
        return getInstance();
    }

    /**
     * 注册事件源
     */
    public  Observable register(@NonNull Object tag){
        List subjectList=subjectMapper.get(tag);
        if (subjectList==null){
            subjectList=new ArrayList();
            subjectMapper.put(tag,subjectList);
        }
        Subject subject;
        subjectList.add(subject=PublishSubject.create());
        return subject;
    }

    public void unregister(@NonNull Object tag){
        List subjects=subjectMapper.get(tag);
        if (subjects!=null){
            subjectMapper.remove(tag);
        }
    }

    /**
     * 取消监听
     */
    public RxBus unregister(@NonNull Object tag,@NonNull Observable observable){
        if (observable==null){
            return getInstance();
        }
        List subjects=subjectMapper.get(tag);
        if (subjects!=null){
            subjects.remove(observable);
            if (isEmpty(subjects)){
                subjectMapper.remove(tag);
            }
        }
        return getInstance();
    }

    public void post(@NonNull Object content){
        post(content.getClass().getName(),content);
    }

    /**
     * 触发事件
     */
    public void post(@NonNull Object tag,@NonNull Object content){
        List subjectList=subjectMapper.get(tag);
        if (!isEmpty(subjectList)){
            for (Subject subject:subjectList){
                subject.onNext(content);
            }
        }
    }

    public static boolean isEmpty(Collection collection){
        return collection==null||collection.isEmpty();
    }
} 
  

3.RxManager代码

/**
 * 用于管理单个presenter的RxBus的事件和RxJava相关代码的生命周期处理
 */
public class RxManager {
    public RxBus mRxBus=RxBus.getInstance();
    //管理rxbus订阅
    private Map> mObservables=new HashMap<>();
    //管理Observables和Subscribers订阅
    private CompositeDisposable mCompositeDisposable=new CompositeDisposable();
    /**
     * RxBus注入监听
     */
    public  void on(String eventName, Consumer action1){
        Observable mObservable=mRxBus.register(eventName);
        mObservables.put(eventName,mObservable);
        Disposable subscription=mObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1, new Consumer() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
        //订阅管理
        mCompositeDisposable.add(subscription);
    }

    /**
     * 单纯的Observables 和 Subscribers管理
     */
    public void add(Disposable m){
        //订阅管理
        mCompositeDisposable.add(m);
    }

    /**
     * 单个presenter生命周期结束,取消订阅和所有rxbus观察
     */
    public void clear(){
        mCompositeDisposable.dispose();
        for (Map.Entry> entry:mObservables.entrySet()){
            mRxBus.unregister(entry.getKey(),entry.getValue());// 移除rxbus观察
        }
    }

    public void unregister(String tag){
        Observable observable=mObservables.remove(tag);
        if (observable!=null){
            mRxBus.unregister(tag,observable);//移除rxbus观察
        }
    }

    //发送rxbus
    public void post(Object tag,Object content){
        mRxBus.post(tag,content);
    }
}

4.消息类别

public class Constants {
    //event bus
    public static final String SEDN_MESSAGE = "send message";
}

5.BaseActivity

public abstract class BaseActivity extends AppCompatActivity {
    public RxManager mRxManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRxManager=new RxManager();
        setContentView(getLayoutId());
        initPresenter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRxManager.clear();
    }

    /*********************
     * 子类实现
     *****************************/
    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    public abstract void initPresenter();

    //获取布局文件
    public abstract int getLayoutId();
}

6.使用方法(可发送对象和任何数据类型)

public class EventMsg {
    public String msg;
    public int year;
}


//发送消息
EventMsg eventMsg=new EventMsg();
eventMsg.msg="淡泊以明志,宁静以致远";
eventMsg.year=3;
mRxManager.post(Constants.SEDN_MESSAGE,eventMsg);


//在返回的ac中接收消息
mRxManager.on(Constants.SEDN_MESSAGE, new Consumer() {
      @Override
      public void accept(Object o) throws Exception {
           EventMsg eventMsg= (EventMsg) o;
           tv_text.setText(eventMsg.msg+eventMsg.year);
      }
}); 
  

 

你可能感兴趣的:(android)