EventBus的使用,以及源碼分析

EventBus的使用捐下,以及源碼分析

EventBus的使用

EventBus能夠簡化各組件間的通信到腥,能夠有效的分離事件的發(fā)送方和接收方朵逝,能避免復(fù)雜和容易出錯的依賴性和生命周期的問題。

EventBus的三要素

  • Event事件左电,可以是任意類型廉侧。
  • Subscriber事件訂閱者页响,需要進(jìn)行注冊篓足。
  • Publisher事件的發(fā)布者。

EventBus的用法

添加依賴

implementation 'org.greenrobot:eventbus:3.1.1'

注冊事件

override fun onStart() {
    EventBus.getDefault().register(this)
    super.onStart()
}

當(dāng)我們需要在Activity或Fragment里訂閱事件的時候闰蚕,我們需要注冊EventBus栈拖。我們一般選擇在onStart()里去注冊。onStop()里去解除没陡。

解除事件

override fun onStop() {
    EventBus.getDefault().unregister(this)
    super.onStop()
}

解除事件一定需要涩哟,為了防止內(nèi)存泄漏。

發(fā)送事件

EventBus.getDefault().post("發(fā)送EventBus事件盼玄,任何類型都可以贴彼。")

處理事件

@Subscribe(threadMode = ThreadMode.MAIN)
fun MessageEventPost(message: String) {
    //todo
}

EventBus注解參數(shù)

注解代碼

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
    ThreadMode threadMode() default ThreadMode.POSTING;
    boolean sticky() default false;
    int priority() default 0;
}

threadMode():運行在那個線程,枚舉類型埃儿。(POSTING,MAIN,MAIN_ORDERED,BACKGROUND,ASYNC)
sticky():是否是粘性事件器仗。

所謂粘性事件,就是在發(fā)送事件之后再訂閱該事件也能收到該事件童番。

priority():優(yōu)先級(0-100)

EventBus源碼分析

EventBus注冊代碼

  public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //通過subscriberMethodFinder 來找到訂閱者訂閱了哪些事件.返回一個 SubscriberMethod 對象的 List, SubscriberMethod里包含了這個方法的 Method 對象,
        //以及將來響應(yīng)訂閱是在哪個線程的 ThreadMode ,以及訂閱的事件類型 eventType ,以及訂閱的優(yōu)先級 priority ,
        //以及是否接收粘性 sticky 事件的 boolean 值精钮,其實就是解析這個類上的所有 Subscriber 注解方法屬性。
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }
       
    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //先在緩存中讀取
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //ignoreGeneratedIndex 默認(rèn)值為false剃斧,findUsingInfo(Class<?> subscriberClass)
        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            //訂閱者Class存入緩存
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
    
    
    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        //獲取FindState()
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //findState.subscriberInf == null is true
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                //核心代碼
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }
    
     private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // 通過發(fā)射獲取訂閱類的所有方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        for (Method method : methods) {
            //獲取類的修飾符
            int modifiers = method.getModifiers();
            //找到所有聲明為public的方法
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                //獲取參數(shù)的class
                Class<?>[] parameterTypes = method.getParameterTypes();
                //只可以包含一個參數(shù)
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        //獲取事件的Class轨香,也就是方法參數(shù)的Class
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            // 獲取 ThreadMode
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 往集合里面添加 SubscriberMethod ,解析方法注解所有的屬性
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                    throw new EventBusException("@Subscribe method " + methodName +
                            "must have exactly 1 parameter but has " + parameterTypes.length);
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }

執(zhí)行完subscriberMethodFinder.findSubscriberMethods(subscriberClass);會通過類對象的 class 去解析這個類中的所有 Subscribe 注解方法的所有屬性值幼东,一個注解方法對應(yīng)一個 SubscriberMethod 對象臂容,包括 threadMode科雳,priority,sticky策橘,eventType炸渡,method。效果如下圖:


image.png

接下來看subscribe這個方法丽已,該方法把subscriber蚌堵,SubscriberMethod分別存好,存入如下兩個集合:

//key 是 Event 參數(shù)的類 -> 上面的String.class
//value 是存放Subscription的集合 Subscription里面包含兩個類 一個是subscriber訂閱者(反射執(zhí)行對象)沛婴,一個是SubscriberMethod     注解方法的所有屬性參數(shù)值
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

// key 是所有的訂閱者
// value 是所有訂閱者里面方法的參數(shù)的 class吼畏,eventType
private final Map<Object, List<Class<?>>> typesBySubscriber;

subscribe方法如下:

    
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //subscriber MainActivity eventType = String
        Class<?> eventType = subscriberMethod.eventType;
        //將MainActivity 和 SubscriberMethod 再次封裝
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //獲取訂閱了此事件類的所有訂閱者列表
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            //線程安全的ArrayList
            subscriptions = new CopyOnWriteArrayList<>();
            //添加
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        //處理優(yōu)先級
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        //通過subscriber 獲取 List<Class<?>>
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        //將事件類加入 訂閱者事件列表中
        subscribedEvents.add(eventType);
        //粘性處理事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

subscriptionsByEventType 集合架構(gòu)圖如下:

image.png

EventBus post代碼

遍歷剛剛的map,拿到map的內(nèi)容嘁灯,通過反射進(jìn)行方法的調(diào)用

    public void post(Object event) {
        //event:"發(fā)送EventBus事件泻蚊,任何類型都可以。"
        //currentPostingThreadState 是一個 ThreadLocal
        PostingThreadState postingState = currentPostingThreadState.get();
        //獲取到線程獨有的變量
        List<Object> eventQueue = postingState.eventQueue;
        //將事件加入隊列
        eventQueue.add(event);
        
        if (!postingState.isPosting) {
            //判斷是否是主線程
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                //循環(huán)遍歷隊列丑婿,發(fā)送單個事件調(diào)用postSingleEvent
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
    
    
      private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        //獲取事件的Class String.class
        Class<?> eventClass = event.getClass();
        //是否找到訂閱者
        boolean subscriptionFound = false;
        // 是否支持事件繼承性雄,默認(rèn)true
        if (eventInheritance) {
            //查找eventClass 所有的父類和接口
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                //依次向eventClass的父類或接口的訂閱方法發(fā)送事件
                Class<?> clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }
    
    
        private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            //得到Subscription列表
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            //遍歷 subscriptions
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    //發(fā)送事件
                    postToSubscription(subscription, event, postingState.isMainThread);
                    //是否被取消了
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }
    
    
        private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        // 根據(jù)不同的線程模式執(zhí)行對應(yīng)
        switch (subscription.subscriberMethod.threadMode) {
            //和發(fā)送事件處于同一線程
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            //主線程
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            //子線程
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(subscription, event);
                }
                break;
            //和發(fā)送事件處于不同線程
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市羹奉,隨后出現(xiàn)的幾起案子秒旋,更是在濱河造成了極大的恐慌,老刑警劉巖诀拭,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件迁筛,死亡現(xiàn)場離奇詭異,居然都是意外死亡耕挨,警方通過查閱死者的電腦和手機细卧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來筒占,“玉大人贪庙,你說我怎么就攤上這事『采唬” “怎么了止邮?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長革骨。 經(jīng)常有香客問我农尖,道長,這世上最難降的妖魔是什么良哲? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任盛卡,我火速辦了婚禮,結(jié)果婚禮上筑凫,老公的妹妹穿的比我還像新娘滑沧。我一直安慰自己并村,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布滓技。 她就那樣靜靜地躺著哩牍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪令漂。 梳的紋絲不亂的頭發(fā)上膝昆,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天,我揣著相機與錄音叠必,去河邊找鬼荚孵。 笑死,一個胖子當(dāng)著我的面吹牛纬朝,可吹牛的內(nèi)容都是我干的收叶。 我是一名探鬼主播,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼共苛,長吁一口氣:“原來是場噩夢啊……” “哼判没!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起隅茎,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤澄峰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后患膛,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體摊阀,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡耻蛇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年踪蹬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片臣咖。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡跃捣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出夺蛇,到底是詐尸還是另有隱情疚漆,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布刁赦,位于F島的核電站娶聘,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏甚脉。R本人自食惡果不足惜丸升,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望牺氨。 院中可真熱鬧狡耻,春花似錦墩剖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至沼头,卻和暖如春爷绘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背进倍。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工揉阎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人背捌。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓毙籽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親毡庆。 傳聞我的和親對象是個殘疾皇子坑赡,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,834評論 2 345