Android EventBus

自学了视频的内容,整理成笔记,方便查阅和复习。

一、简介

EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序内各组件间、组件与后台线程间的通信。比如请求网络,等网络返回时通过Handler或Broadcast通知UI,两个Fragment之间需要通过Listener通信,这些需求都可以通过EventBus实现。

下载地址:https://github.com/greenrobot/EventBus

 

二、使用步骤

1、添加jar包到libs文件夹下

2、注册

EventBus.getDefault().register(this);

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

}

3、解注册

EventBus.getDefault().unregister(this);

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

4、构造发送消息类

public class MessageEvent {
    public String name;
    public String password;

    public MessageEvent(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

5、发布消息

EventBus.getDefault().post(new MessageEvent("dahaige","123456"));

6、接收消息

1)ThreadMode.MAIN 表示这个方法在主线程中执行 ----主线程

2)ThreadMode.BACKGROUND 表示该方法在后台执行,不能并发处理 ----子线程

3)ThreadMode.ASYNC 也表示在后台执行,可以异步并发处理。----子线程

4)ThreadMode.POSTING 表示该方法和消息发送方在同一个线程中执行  ----发送方在主线程,接收方就在主线程;发送方在子线程,接收方就在子线程。

@Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBus(MessageEvent event){
        tv_result.setText("name:"+event.name+" passwrod:"+event.password);
    }

 

三、粘性事件

1、简介

之前说的使用方法, 都是需要先注册(register), 再post,才能接受到事件; 
如果你使用postSticky发送事件, 那么可以不需要先注册, 也能接受到事件。

2、构造发送消息类

public class StickyEvent {
    public String msg;

    public StickyEvent(String msg) {
        this.msg = msg;
    }
}

3、发布消息

EventBus.getDefault().postSticky(new StickyEvent("我是粘性事件"));

4、接收消息

    //注意,和之前的方法一样,只是多了一个 sticky = true 的属性.
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(StickyEvent event){
        tv_c_result.setText(event.msg);
    }

5、注册

EventBus.getDefault().register(CActivity.this);

6、解注册

EventBus.getDefault().removeAllStickyEvents();
EventBus.getDefault().unregister(CActivity.class);

四、例子 

布局:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atguigu.android.atguigu.activity.EventBusActivity"
    android:orientation="vertical">

    <include layout="@layout/titlebar"/>

    <Button
        android:id="@+id/send"
        android:text="跳转到发送页面"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/send_sticky"
        android:text="发送粘性事件跳转到发送页面"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:text="结果显示"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atguigu.android.atguigu.activity.EventBusSendActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/send_main"
        android:text="主线程发送数据"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/receive_sticky"
        android:text="接收粘性事件"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:text="显示结果"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

代码:

public class EventBusActivity extends Activity implements View.OnClickListener{
    private Button send;
    private Button send_sticky;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eventbus);
        send = (Button)findViewById(R.id.send);
        send_sticky = (Button)findViewById(R.id.send_sticky);
        text = (TextView)findViewById(R.id.text);
        send.setOnClickListener(this);
        send_sticky.setOnClickListener(this);

        //1.注册
        EventBus.getDefault().register(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send://跳转到发送页面
                Intent intent = new Intent(this,EventBusSendActivity.class);
                startActivity(intent);
                break;
            case R.id.send_sticky://发送粘性事件跳转到发送页面
                //2.发送粘性事件
                EventBus.getDefault().postSticky(new StickyEvent("发送粘性事件..."));
               //3.跳转到发送页面
                Intent intent2 = new Intent(this,EventBusSendActivity.class);
                startActivity(intent2);
                break;
        }
    }

    //5.接收消息
    @Subscribe(threadMode = ThreadMode.MAIN) //主线程
    public void MessageEventBus(MessageEvent event){
        //显示接收到的数据
        text.setText(event.name);
    }

    //2.解注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
public class EventBusSendActivity extends Activity implements View.OnClickListener{
    private Button send_main;
    private Button receive_sticky;
    private TextView text;
    private boolean flag = true;

    @Override
    public boolean releaseInstance() {
        return super.releaseInstance();
    }

    @Override
    public void triggerSearch(String query, @Nullable Bundle appSearchData) {
        super.triggerSearch(query, appSearchData);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_bus_send);
        send_main = (Button) findViewById(R.id.send_main);
        receive_sticky = (Button)findViewById(R.id.receive_sticky);
        text = (TextView)findViewById(R.id.text);

        send_main.setOnClickListener(this);
        receive_sticky.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send_main:
                //4.发送消息
                EventBus.getDefault().post(new MessageEvent("主线程发送的数据..."));
                finish();
                break;

            case R.id.receive_sticky:
                if(flag){
                    //5.注册
                    EventBus.getDefault().register(this);
                    flag = false;
                }
                break;
        }
    }

    //4.接收粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void StickyEventBus(StickyEvent event){
        //显示接收的数据
        text.setText(event.msg);
    }

    //6.解注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解注册之前移除所有的粘性事件
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(this);
    }
}
public class MessageEvent {
    public String name;

    public MessageEvent(String name) {
        this.name = name;
    }
}
public class StickyEvent {
    public StickyEvent(String msg) {
        this.msg = msg;
    }

    public String msg;

}

五、源码分析

1、注册(订阅)源码分析

        EventBus.getDefault().register(CActivity.this);

// 1 注册
public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();

        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
}

            1.0 EventBus.getDefault()

    public static EventBus getDefault() {
		// 单例设计
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }
  // 可以看出来,EventBus是单例模式存在的,一个项目中只能有一个EventBus这样有利于管理订阅者和订阅方法,这会在下面的介绍中体现出来。  


 public EventBus() {
        this(DEFAULT_BUILDER);
  }
//EventBus采用双重校验锁设计为一个单例模式
//奇怪的在于虽然设计为单例模式,但是构造方法确实public类型。
//EventBus默认支持一条事件总线,通常是通过getDefault()方法获取EventBus实例,但也能通过直接new EventBus这种最简单的方式获取多条事件总线,彼此之间完全分开。

            1.1 订阅方法的实体类

// 1.1 订阅方法的实体类
public class SubscriberMethod {
    final Method method;		            // 方法
    final ThreadMode threadMode;	        // 执行线程
    final Class<?> eventType;		        // 接收事件类型
    final int priority;						// 优先级
    final boolean sticky;					// 粘性事件
    /** Used for efficient comparison */
    String methodString;

    public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
        this.priority = priority;
        this.sticky = sticky;
    }

	//。。。。
}

            1.2 从订阅类中获取所有的订阅方法信息;

从注解器中获取比较快,利用反射获取比较慢。一般先执行从注解器中获取,注解不到再通过反射。

// 1.2 从订阅类中获取所有的订阅方法信息;
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {

		// 首先从缓存中读取
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

		// 默认false
        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;
        }
    }

                1.2.1 反射来获取订阅方法信息findUsingReflection()

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {

        FindState findState = prepareFindState();

        findState.initForSubscriber(subscriberClass);

        while (findState.clazz != null) {
			// 取订阅类的方法信息
            findUsingReflectionInSingleClass(findState);

            findState.moveToSuperclass();
        }
		
		// 释放findState集合,并返回订阅类的方法
        return getMethodsAndRelease(findState);
    }

FindState其实就是一个里面保存了订阅者和订阅方法信息的一个实体类,包括订阅类中所有订阅的事件类型和所有的订阅方法等。

我们看到会首先创建一个FindState对象并执行findUsingReflectionInSingleClass(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;
        }

		// 遍历所有方法,忽略private类型的,最后如果是公有,并且不是 
		// java编译器 生成的方法名,那么就是我们要的了。
        for (Method method : methods) {
            int modifiers = method.getModifiers();

            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 1) {

                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);

					// 保证只有一个事件参数
                    if (subscribeAnnotation != null) {

                        Class<?> eventType = parameterTypes[0];

						// 校验是否添加该方法
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
							
							// 添加方法
                            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");
            }
        }
    }


//可以看到,首先会得到订阅类的class对象并通过反射获取订阅类中的所有方法信息
//然后通过筛选获取到订阅方法集合。
//程序执行到此我们就获取到了订阅类中的所有的订阅方法信息

                1.2.2 通过注解获取订阅方法信息findUsingInfo()

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
		// 从FIND_STATE_POOL数组中查找FindState,命中返回,否则直接new
        FindState findState = prepareFindState();

		// 初始化FindState
        findState.initForSubscriber(subscriberClass);

        while (findState.clazz != null) {
            findState.subscriberInfo = getSubscriberInfo(findState);

			// findState.subscriberInfo默认null
            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);
    }

                    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;
        }

		// 遍历所有方法,忽略private类型的,最后如果是公有,并且不是 
		// java编译器 生成的方法名,那么就是我们要的了。
        for (Method method : methods) {
            int modifiers = method.getModifiers();

            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 1) {

                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);

					// 保证只有一个事件参数
                    if (subscribeAnnotation != null) {

                        Class<?> eventType = parameterTypes[0];

						// 校验是否添加该方法
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
							
							// 添加方法
                            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");
            }
        }
    }


//可以看到,首先会得到订阅类的class对象并通过反射获取订阅类中的所有方法信息,然后通过筛选获取到订阅方法集合。

//程序执行到此我们就获取到了订阅类中的所有的订阅方法信息

            1.3 注册订阅方法subscribe()

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
		// 获取订阅方法的事件类型
        Class<?> eventType = subscriberMethod.eventType;

        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
		// 根据订阅的事件类型获取所有的订阅者
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);

		// 将订阅者添加到subscriptionsByEventType集合中
        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;
            }
        }

 		// 获取订阅者所有订阅的事件类型
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }

		// 将该事件类型添加到typesBySubscriber中
        subscribedEvents.add(eventType);

		// 如果接收sticky事件,立即分发sticky事件
        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);
            }
        }
    }

            1.4 小结
                1.4.1 首先获取订阅方法的参数类型即订阅事件类型 (获取不同订阅者中相同的类型)
                1.4.2 根据订阅事件类型获取该事件类型的所有订阅者
                1.4.3 将该订阅者添加到该事件类型的订阅者集合中即:subscriptionsByEventType(将不同activity的String类添加进去subscriptionsByEventType集合中)
                1.4.4 获取订阅者所有的订阅事件类型(获取一个订阅者中的所有类型)
                1.4.5 将该事件类型添加到该订阅者的订阅事件类型集中即:typesBySubscriber(将String类和MessageEvent对象 都添加进typesBySubscriber集合中,解注册的时候循环遍历,依次从subscriptionsByEventType集合中删除)
                注册流程图

 

 

2、发布消息源码分析

        2.EventBus.getDefault().post("发送普通数据");

public void post(Object event) {

		// 获取当前线程的postingState
        PostingThreadState postingState = currentPostingThreadState.get();

		// 取得当前线程的事件队列
        List<Object> eventQueue = postingState.eventQueue;

		// 将该事件添加到当前的事件队列中等待分发
        eventQueue.add(event);

        if (!postingState.isPosting) {
			// 判断是否是在主线程post
            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;
            }
        }
    }

            2.1 PostingThreadState

final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>();//当前线程的事件队列
        boolean isPosting;				// 是否有事件正在分发
        boolean isMainThread;		// post的线程是否是主线程
        Subscription subscription;	// 订阅者
        Object event;						// 订阅事件
        boolean canceled;				// 是否取消
    }

            2.2 postSingleEvent  发送事件

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
		// 得到事件类型
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;

		// 是否触发订阅了该事件(eventClass)的父类,以及接口的类的响应方法.
        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);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

                postSingleEventForEventType

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
			// 根据事件类型获取所有的订阅者
            subscriptions = subscriptionsByEventType.get(eventClass);
        }

		// 向每个订阅者分发事件
        if (subscriptions != null && !subscriptions.isEmpty()) {
			
			// 循环向每个订阅者发送事件
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    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;
    }

                    postToSubscription

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {

        switch (subscription.subscriberMethod.threadMode) {
            case POSTING://默认的 ThreadMode,表示在执行 Post 操作的线程直接调用订阅者的事件响应方法,
            //不论该线程是否为主线程(UI 线程)。
                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);
        }
    }

                        invokeSubscriber

//最终通过反射调用订阅者的订阅函数 并把event作为参数传入
     void invokeSubscriber(Subscription subscription, Object event) {
        try {
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

            2.3 小结
                2.3.1 首先获取当前线程的PostingThreadState对象从而获取到当前线程的事件队列
                2.3.2 通过事件类型获取到所有订阅者集合
                2.3.3 通过反射执行订阅者中的订阅方法
                post流程图

 

 

3、取消注册源码分析

        3.EventBus.getDefault().unregister(this);

    public synchronized void unregister(Object subscriber) {
		//获取订阅者的所有订阅的事件类型
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);

        if (subscribedTypes != null) {

            for (Class<?> eventType : subscribedTypes) {
				//从事件类型的订阅者集合中移除订阅者
                unsubscribeByEventType(subscriber, eventType);
            }

            typesBySubscriber.remove(subscriber);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

            3.1 unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
		//获取该订阅者的所有事件类型
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);

		// 遍历订阅者集合,将解除的订阅者移除
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

 

            3.2 小结
                3.2.1 首先获取订阅者所有订阅事件
                3.2.2 遍历订阅事件
                3.2.3 根据订阅事件获取所有的订阅了该事件的订阅者集合
                3.2.4 将该订阅者移除
                3.2.5 将步骤1中的集合中的订阅者移除

六、总结

    (1)EventBus总线接收消息四大线程
    (2)粘性事件的特点
    (3)注册源码分析

        1、通过反射或注解获取所有的订阅方法
        2、将当前订阅者添加到Eventbus总的事件订阅者的集合中
        3、将当前订阅者所有订阅的事件类型添加到typeBySubscriber中

    (4)发送源码分析

        1、得到要发送的事件类型
        2、根据事件类型获取所有订阅者,并循环向每个订阅者发送。

    (5)解注册源码分析

        1、通过typeBySubscriber获取当前订阅者所有的事件类型
        2、循环遍历每一个事件类型,并删除当前订阅者的订阅的方法

 

参考:http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html

           http://www.2cto.com/kf/201607/524998.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值