【寫(xiě)框架】基于RxJava2,高仿EventBus打造RxBus2

If you just a little want,you will only get a little.

1# 概述

Android 社區(qū)有名的事件總線(xiàn)庫(kù)有EventBusotto。后者為支持RxJava而主動(dòng)Deprecated。可以看得出Otto的創(chuàng)建者非常大度,另一方面也說(shuō)明了RxJava能更好地實(shí)現(xiàn)事件總線(xiàn)。(JakeWharton也是RxJava的主要貢獻(xiàn)者)。
為減少讀者學(xué)習(xí)成本,本文高仿EventBus來(lái)打造一個(gè)基于RxJava2的小型事件總線(xiàn)RxBus2。如果在過(guò)程中大家看到EventBus的影子不必驚慌,說(shuō)明你對(duì)EventBus吃得比較透。
通過(guò)本文可以GET
Flowable的創(chuàng)建,過(guò)濾,線(xiàn)程調(diào)度,訂閱,事件發(fā)射,F(xiàn)lowable的取消,自定義注解,反射獲取方法信息,反射調(diào)用方法等知識(shí)點(diǎn)的膚淺認(rèn)識(shí)。如果不感興趣可以先走一步。

2# 基本操作

既然是高仿,RxBus2的API命名方式也得和EventBus保持一致。基本操作如下:

  • 注冊(cè)
  • 注解方式處理事件
  • 發(fā)射事件
  • 取消注冊(cè)

首先以單例模式提供RxBus,構(gòu)造方法內(nèi)創(chuàng)建了FlowableProcessor和SubscriberMethodFinder。FlowableProcessor(來(lái)自RxJava2)對(duì)應(yīng)RxJava中的PublishSubject,是Flowable版的Subject,僅會(huì)向Subsciber發(fā)射在訂閱之后Flowable發(fā)射的數(shù)據(jù)。SubscriberMethodFinder來(lái)自EventBus,用于解析注解方法,具體使用后面會(huì)講到。

private RxBus() {
        mFlowableProcessor = PublishProcessor.create().toSerialized();
        mSubscriberMethodFinder = new SubscriberMethodFinder();
    }

    public static RxBus getDefault() {
        if (mRxBus == null) {
            synchronized (RxBus.class) {
                if (mRxBus == null) {
                    mRxBus = new RxBus();
                }
            }
        }
        return mRxBus;
    }

2.1# 注冊(cè)

public void register(Object subsciber) {
        Class<?> subsciberClass = subsciber.getClass();
        List<SubscriberMethod> subscriberMethods = mSubscriberMethodFinder.findSubscriberMethods(subsciberClass);
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            addSubscriber(subsciber, subscriberMethod);
        }
    }

采用反射方式獲取Subscribe注解方法的信息,包括Method對(duì)象,參數(shù)類(lèi)型,線(xiàn)程模式。閱讀過(guò)EventBus源碼的同學(xué)可以跳過(guò),避免產(chǎn)生不屑之情。

public List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = findUsingReflection(subscriberClass);
        if (subscriberMethods.isEmpty()) {
            throw new RxBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        }
        return subscriberMethods;
    }

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>();
        Method[] methods = subscriberClass.getDeclaredMethods();
        for (Method method : methods) {
            int modifiers = method.getModifiers();
             //@Subscribe 的注解方法必須是 public, non-static, and non-abstract
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                //@Subscribe 的注解方法只能且必須有一個(gè)參數(shù)
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                     //必須有@Subscribe 注解
                    if (subscribeAnnotation != null) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        Class<?> eventType = parameterTypes[0];
                        subscriberMethods.add(new SubscriberMethod(method, eventType, getThreadMode(threadMode)));
                    }
                }
            }
        }
        return subscriberMethods;
    }

完成Subscribe注解方法解析后,根據(jù)方法信息生成訂閱者,并存儲(chǔ)返回的Disposable,以便以后取消注冊(cè)用。

private void addSubscriber(final Object subsciber, final SubscriberMethod subscriberMethod) {
        Class<?> subsciberClass = subsciber.getClass();
        Class<?> eventType = subscriberMethod.getEventType();
        //ofType事件過(guò)濾,observeOn線(xiàn)程調(diào)度,subscribe訂閱回調(diào)
        Disposable disposable = mFlowableProcessor.ofType(eventType).observeOn(subscriberMethod.getThreadMode())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        invokeMethod(subsciber, subscriberMethod, o);//反射調(diào)用注解方法
                    }
                });
        //Map<SubscriberClass,Map<EventTypeClass,Disposable>>存儲(chǔ)Disposable作取消事件之用
        Map<Class<?>, Disposable> disposableMap = mDisposableMap.get(subsciberClass);
        if (disposableMap == null) {
            disposableMap = new HashMap<>();
            mDisposableMap.put(subsciberClass, disposableMap);
        }
        disposableMap.put(eventType, disposable);
    }

反射調(diào)用注解方法

private void invokeMethod(Object subscriber, SubscriberMethod subscriberMethod, Object obj) {
        try {
            subscriberMethod.getMethod().invoke(subscriber, obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

2.2# 發(fā)射事件

不管有沒(méi)訂閱者都進(jìn)行發(fā)射,以備擴(kuò)展Sticky事件(目前沒(méi)實(shí)現(xiàn))

public void post(Object obj) {
        mFlowableProcessor.onNext(obj);
    }

2.3# 取消注冊(cè)

取消注冊(cè)有兩種,原理是取出存儲(chǔ)在Map中的 Disposable進(jìn)行dispose(),然后remove。

  • 根據(jù)訂閱者取消(取消訂閱者中所有的訂閱方法)
public void unregister(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        Map<Class<?>, Disposable> disposableMap = mDisposableMap.get(subscriberClass);
        if (disposableMap == null) {
            throw new IllegalArgumentException(subscriberClass.getSimpleName() + " haven't registered RxBus");
        }
        Set<Class<?>> keySet = disposableMap.keySet();
        for (Class<?> evenType : keySet) {
            Disposable disposable = disposableMap.get(evenType);
            disposable.dispose();
        }
        mDisposableMap.remove(subscriberClass);
    }
  • 根據(jù)訂閱事件類(lèi)型取消(僅取消訂閱者特定事件類(lèi)型的訂閱方法)
public void unregister(Object subscriber, Class<?> eventType) {
        Class<?> subscriberClass = subscriber.getClass();
        Map<Class<?>, Disposable> disposableMap = mDisposableMap.get(subscriberClass);
        if (disposableMap == null) {
            throw new IllegalArgumentException(subscriberClass.getSimpleName() + " haven't registered RxBus");
        }
        if (!disposableMap.containsKey(eventType)) {
            throw new IllegalArgumentException("The event with type of " + subscriberClass.getSimpleName() + " is not" +
                    " required in " + subscriberClass.getSimpleName());
        }
        Disposable disposable = disposableMap.get(eventType);
        disposable.dispose();
        mDisposableMap.remove(eventType);
    }

總結(jié)

基于RxJava打造RxBus可謂物盡其用。RxJava管理著可觀測(cè),可控制的事件序列,比起EventBus有更多得天獨(dú)厚的優(yōu)勢(shì),它的線(xiàn)程調(diào)度,各種類(lèi)型的操作符,使得在實(shí)際運(yùn)用中可以在事件控制方面進(jìn)行大量的自定義操作。
對(duì)本文源碼有興趣的同學(xué)可以在此傳送RxBus2

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容