EventBus的使用与原理

来源:互联网 发布:声音剪辑合成软件 编辑:程序博客网 时间:2024/05/23 14:44

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下载