EventBus的使用與原理

EventBus是一款針對Android優化的發佈/訂閱事件總線。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優點是開銷小,代碼更優雅。以及將發送者和接收者解耦。
使用方法如下:首先在gradle中進行配置

compile 'org.greenrobot:eventbus:3.0.0'

新建一個消息類

public class AnyEvent {

    private String discribe;

    public AnyEvent(String discribe) {
        this.discribe = discribe;
    }

    public String getDiscribe() {
        return discribe;
    }
}

接着在想要接收消息的類中註冊,以Activity爲例

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

並且在該類中添加處理消息的函數

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(AnyEvent event) {
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainMessageEvent(AnyEvent event) {
    };

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onBackgroundMessageEvent(AnyEvent event) {
    };

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onAsyncMessageEvent(AnyEvent event) {
    };

需要注意的是函數必須添加@Subscribe(threadMode = ThreadMode.POSTING)這樣的註釋,其中threadMode代表了消息處理所處的線程,
一共有四個,分別是:
ThreadMode.POSTING,接收事件和分發事件在一個線程中執行
ThreadMode.MAIN,不論分發事件在哪個線程運行,接收事件永遠在UI線程執行
ThreadMode.BACKGROUND,如果分發事件在子線程運行,那麼接收事件直接在同樣線程運行,如果分發事件在UI線程,那麼會啓動一個子線程運行接收事件
ThreadMode.ASYNC,無論分發事件在(UI或者子線程)哪個線程執行,接收都會在另外一個子線程執行
函數名可以自己取,但是參數必須只有一個,類型隨意
最後是發送消息的方法

EventBus.getDefault().post(new AnyEvent("hello world"));

這樣就可以使用EventBus進行消息的發送以及處理,下面我們分析下EventBus的使用原理。
首先看註冊時做了什麼

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

List中我們看下SubscriberMethod的定義

public class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;
    final int priority;
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;
    ......
    ......
    ......
}

應該能看出來,SubscriberMethod是用來存儲某個函數的信息的,其中threadMode就是我們當初註釋添加的信息,即在哪個線程執行的信息,而
eventType則是函數中的參數的類型,回到register方法中,我們去看下findSubscriberMethods的具體實現

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //從緩存中取
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        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 {
            //存入緩存
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

功能的具體實現應該是在中間的findUsingReflection方法中,繼續查看

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

沒什麼好看的。。。具體的實現是在findUsingReflectionInSingleClass方法中

private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            //獲得註冊類的所有方法
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            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) {
                //獲取方法的參數
                Class<?>[] parameterTypes = method.getParameterTypes();
                //參數必須是一個
                if (parameterTypes.length == 1) {
                    //我們的方法必須有@Subscribe這個註釋
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                                //將方法的具體信息添加到findState.subscriberMethods中                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } 
    ......
    ......
    ......
            }
        }
    }

這樣就完成了訂閱者處理方法信息的獲取,現在我們還是回到register方法裏

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

經過上面的步驟,List subscriberMethods中是我們處理消息的方法的各種參數,subscribe(subscriber, subscriberMethod)負責存儲,subscriber爲訂閱的具體對象,subscriberMethod爲訂閱的處理方法的參數

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            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();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }
    ......
    ......
    ......
    }

具體的信息儲存在subscriptionsByEventType中,他的定義爲

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

其中鍵爲Class< ? >類型,具體就是subscriberMethod.eventType,前面我們說過,它代表我們處理方法中的參數類型;值爲CopyOnWriteArrayList,我們來看Subscription的定義

final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
    ......
    ......
    ......
}

subscriber是訂閱對象,subscriberMethod爲方法信息,所以訂閱信息就是用一個Map對象存儲,其中鍵值分別爲方法參數和方法信息。
接着我們看看發送消息做了什麼

public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

沒有什麼重要邏輯,接着看postSingleEvent方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        ......
        ......
        ......
    }

關鍵的代碼在postSingleEventForEventType中,我們接着往下看

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        ......
        ......
        ......
        postToSubscription(subscription, event, postingState.isMainThread);
        ......
        ......
        ......
    }

我們可以看到,先從subscriptionsByEventType中取出發送的消息類型所對應的值,接着調用postToSubscription發送消息

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            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);
        }
    }

發送消息的具體實現就不繼續了,無非就是新建線程或者利用Handler發送消息等。
Demo下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章