RxJava實(shí)現(xiàn)事件總線 Rxbus代替eventbus 減少庫(kù)的使用

原文地址
什么是Eventbus
EventBus定義:是一個(gè)發(fā)布 / 訂閱的事件總線。 這么說(shuō)應(yīng)該包含4個(gè)成分:發(fā)布者,訂閱者,事件,總線。 那么這四者的關(guān)系是什么呢? 很明顯:訂閱者訂閱事件到總線,發(fā)送者發(fā)布事件。
總結(jié)一下就是:我訂閱你,你遇到事情了,發(fā)送事件,或者理解為更新動(dòng)態(tài),我就收到消息。
常用的地方
Eventbus和Rxbus常用于組件間信息的交換與通知,避免采用廣播以及使用一大堆接口來(lái)實(shí)現(xiàn)。
使用的地方以本次項(xiàng)目來(lái)舉例: 一個(gè)商城界面,包含一個(gè)RecyclerView和LinearLayout,LinearLayout中是一個(gè)購(gòu)物籃信息,也就是美團(tuán)那種。當(dāng)點(diǎn)擊RecyclerView中的按鈕時(shí),商品被添加,LinearLayout中的商品總價(jià)應(yīng)該發(fā)生變化。而這時(shí)候就到了使用Eventbus或者Rxbus的時(shí)候了。 為了增加商品總價(jià),常見(jiàn)的方法有這幾種: 1. 在創(chuàng)建adapter的時(shí)候?qū)inearLayout的對(duì)象一并傳入,以此可以更改LinearLayout中的TextView 2. 設(shè)置廣播事件。添加商品-》發(fā)送廣播-》處理廣播 3. 設(shè)置接口。添加商品-》觸發(fā)接口 4. 使用觀察者模式。也就是Eventbus以及Rxbus實(shí)現(xiàn)的功能。
以上部分抄自一個(gè)網(wǎng)友,有的時(shí)候知道怎么回事就是寫(xiě)不出來(lái);好坑,不多說(shuō)了直接上代碼

public class RxBus {
    private static volatile RxBus defaultInstance;
    // 主題
    private final Subject bus;
    // PublishSubject只會(huì)把在訂閱發(fā)生的時(shí)間點(diǎn)之后來(lái)自原始Observable的數(shù)據(jù)發(fā)射給觀察者
    public RxBus() {
        bus = new SerializedSubject<>(PublishSubject.create());
    }
    // 單例RxBus
    public static RxBus getDefault() {
        RxBus rxBus = defaultInstance;
        if (defaultInstance == null) {
            synchronized (RxBus.class) {
                rxBus = defaultInstance;
                if (defaultInstance == null) {
                    rxBus = new RxBus();
                    defaultInstance = rxBus;
                }
            }
        }
        return rxBus;
    }
    // 提供了一個(gè)新的事件
    public void post (Object o) {
        bus.onNext(o);
    }
    // 根據(jù)傳遞的 eventType 類(lèi)型返回特定類(lèi)型(eventType)的 被觀察者
    public <T> Observable<T> toObserverable (Class<T> eventType) {
        return bus.ofType(eventType);
    }
}


自定義event 實(shí)現(xiàn)數(shù)據(jù)拆分

public class RxEvent {
    public int reciveType;
    public int eventType;
    public String eventAction;
    public  Object event;

    public RxEvent() {
    }

    /**
     * RxBus 事件
     * @param reciveType 接收者類(lèi)型
     * @param eventType 事件類(lèi)型
     * @param eventAction 事件Action
     * @param event       時(shí)間
     */
    public RxEvent(int reciveType, int eventType, String eventAction, Object event) {
        this.reciveType = reciveType;
        this.eventType = eventType;
        this.eventAction = eventAction;
        this.event = event;
    }



    public Object getEvent() {
        return event;
    }

}

在項(xiàng)目中的使用,注意要在activity或者是fragment的start中注冊(cè)Subscription觀察者事件,并且在onDestroy中將解除注銷(xiāo)事件,在android中使用過(guò)程中可以結(jié)合Rxandroid一起使用,

Subscription rxMainBus = RxBus.getDefault().toObserverable(RxEvent.class)
                .filter(rxEvent -> {
        //此處可以通過(guò)Rxjava的filter過(guò)濾函數(shù)對(duì)數(shù)據(jù)進(jìn)行過(guò)濾,從而得到自己想要的數(shù)據(jù)
                    if ((rxEvent.reciveType == IStatics.DATA_BROADCAST || 
                  rxEvent.reciveType ==IStatics.DATA_ALL) && (rxEvent.eventType == 
                  IStatics.EVENT_MAIN || rxEvent.eventType ==IStatics.EVENT_ALL_THREAD)) {
                        return true;
                    }
                    return false;
                })
              //.observeOn(Schedulers.computation())//可以設(shè)置為子線程中接收數(shù)據(jù)
                .observeOn(AndroidSchedulers.mainThread())//設(shè)置為主線程接收數(shù)據(jù)
                .subscribe(new Action1<RxEvent>() {
                               @Override
                               public void call(RxEvent rxEvent) {
                                   switch (rxEvent.eventAction) {
                                      //此處可以根據(jù)事件類(lèi)型分析數(shù)據(jù),一對(duì)應(yīng)不同的操作

                                   }
                               }
                           },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                // TODO: 處理異常
                            }
                        });

特別注意的是一定要在onDestroy中解除事件的注銷(xiāo),以保證不出現(xiàn)內(nèi)存泄漏

if (rxMainBus != null && !rxMainBus.isUnsubscribed()) {    rxMainBus.unsubscribe();}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容