Android--EventBus

1 简介

EventBus是一种用于Android的事件发布-订阅总线(Gihub地址)。它简化了组件之间通信的复杂度,避免广播通信带来的许多不便

Event(事件) ——它可以是任意类型
Subscriber(事件订阅者) ——事件处理的方法名可以随意取,要加上注解@subscribe(),并且指定线程模型,默认是POSTING
Publisher(事件的发布者) 可以在任意线程发布事件,一般情况下使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post()方法即可。



2 依赖和混淆规则

implementation 'org.greenrobot:eventbus:3.1.1'//eventbus

在项目的混淆文件中,加入EventBus 的混淆规则。(可能会出现debug版本测试正常,release版本subscriber 收不到消息等问题)

-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
 
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}



3 使用

3.1 定义事件类EventMessage

public class EventMessage {

    private int type;
    private String message;

    public EventMessage(int type, String message) {
        this.type = type;
        this.message = message;
    }

    public String toString() {
        return "type=" + type + "--message= " + message;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}


3.2 订阅事件

在需要订阅事件的模块中,注册Eventbus。并在该类中创建一个方法来接收事件消息。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);//注册eventbus
        //官方的例子是在onStart()回调方法进行register()
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解注册eventbus
        //官方的例子是在onStop()回调方法进行unregister()
    }

    /**
     * 接收消息事件
     *
     * @param eventMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage eventMessage) {
        Log.d("TAG", "onReceiveMsg: " + eventMessage.toString());
    }

}

🔣创建的这个方法是有要求的:

  1. 该方法有且只有一个参数
  2. 该方法必须是public修饰符修饰,不能用static关键字修饰,不能是抽象的(abstract)
  3. 该方法需要用@Subscribe注解进行修饰

🔣@Subscribe 是作用于方法的的运行时注解,存在3个基础属性: thread、Modesticky、priority


3.3发送事件

在需要发送事件的地方,调用EventBus的post(Object event),postSticky(Object event)来通知订阅者。

EventBus.getDefault().post(new EventMessage(1, "Hello MainActivity"));
EventBus.getDefault().postSticky(new EventMessage(1, "Hello MainActivity"));

post():发送普通事件(订阅者已经注册eventbus,才能接收到这个事件)
postSticky():发送粘性事件(订阅者注册eventbus后接收到这个事件)



4 @Subscribe的3个属性

threadMode

函数运行的线程

属性值说明
POSTING与发送事件同一个线程。
MAIN主线程。如果post在主线程,直接在主线程中运行,会阻塞发布线程,如果post在子线程,则事件排队等待传递,使用handler回调到主线程中
MAIN_ORDERED主线程-排队。不同于MAIN,此模式事件总是排队等待传递,不会阻塞发布线程
BACKGROUND后台线程。如果post在子线程,则在post所在的线程执行;如果post是主线程,则使用单个后台线程按顺序执行
ASYNC异步线程。总是使用异步线程执行,通过线程池管理异步线程,不会阻塞发布线程和主线程

sticky

是否粘性事件,默认是false。
EventBus事件传递是先对订阅者(Subscriber)进行先注册的,然后再post事件的。那sticky的作用是在先post事件,后对订阅者注册这种开发场景的支持。

针对sticky事件 eventBus会缓存在事件发射队列,若是订阅关系已经存在则发射出去,但不会销毁。下次再次订阅,会继续接收上一次事件。
解决方法:

@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onMessageEvent(EventMessage eventMessage){
    Log.d("TAG", "onReceiveMsg: " + eventMessage.toString());
    EventBus.getDefault().removeStickyEvent(eventMessage);
}

priority

事件优先级。
前提是在post事件发布,onMessageEvent事件接收处理这两方的线程环境相同的前提下,才有意义。



5 源码解析

手撕EventBus框架源码,再徒手撸一个

EventBus.getDefault().register(Object subscriber);

    /**
     * 注册对象
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();//获取当前对象的class
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//获取当前类中使用@Subscribe注解的方法列表  ->> 分析点1
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);//遍历注解方法,订阅到当前对象  ->> 分析点2
            }
        }
    }

分析点1: 通过反射获取 @Subscribe 注解的方法列表

 private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();//当前对象(如:XActivity)中使用@Subscribe注解的方法列表 缓存Map,key=当前对象,value=注解方法列表
 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
		//查看缓存中是否存在当前对象的注解方法列表,如果存在直接返回
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);//忽略无关紧要信息最终调用findUsingReflectionInSingleClass()
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);//忽略无关紧要信息最终调用findUsingReflectionInSingleClass()
        }
        if (subscriberMethods.isEmpty()) {//如果没有找到注解方法,抛异常,这就是为什么在没有使用@Subscribe方法的类中尝试register会报错的原因
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);//缓存Map,key=当前对象,value=注解方法列表
            return subscriberMethods;
        }
    }

	//忽略无关紧要信息最终调用findUsingReflectionInSingleClass()
    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
		//忽略代码
        findUsingReflectionInSingleClass(findState);
    }

	//忽略无关紧要信息最终调用findUsingReflectionInSingleClass()
 	private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
		//忽略代码
        findUsingReflectionInSingleClass(findState);
    }

最终获取 @Subscribe 注解的方法列表

  //在单个类中使用反射查找	
  private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            methods = findState.clazz.getDeclaredMethods();//反射获取所有方法(public,private,protected,默认类型 )
        } catch (Throwable th) {
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
		//遍历这个类中的所有方法,接下来无非就获取我们想要的方法(通过@Subscribe注解的方法),解析这个方法相关的信息(方法名称,方法修饰符,参数,以及注解相关的信息)
        for (Method method : methods) {
            int modifiers = method.getModifiers();//方法修饰符
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {//方法修饰类型必须是public=共有的 && 同时(不能抽象的,不能静态的,不能桥接的,不能合成的) ( MODIFIERS_IGNORE == Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC)
                Class<?>[] parameterTypes = method.getParameterTypes();//方法参数类型数组(形参类型)
                if (parameterTypes.length == 1) {//只有一个形参的方法
					//获取注解@Subscribe相关信息
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {//注解不为空,说明此方法是@Subscribe注解的方法,也就是我们寻找的目标方法
                        Class<?> eventType = parameterTypes[0];//获取第一个形参的类型(如:Event.class,String.class)
                        if (findState.checkAdd(method, eventType)) {//校验是否参数是否满足条件,这个我们可以忽略吧
                            ThreadMode threadMode = subscribeAnnotation.threadMode();//获取注解上的信息线程模式(@Subscribe(threadMode = ThreadMode.MAIN))
							//获取其他注解信息(priority=优先级,sticky=是否粘性事件)然后构建SubscriberMethod对象保存到列表
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {//如果开启了严格验证,但是@Subscribe的方法参数超过1个,则抛异常(就是说如果开启了严格验证,@Subscribe注解的方法参数超过1个就会抛异常)
                    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)) {//如果开启了严格校验,但是@Subscribe使用非public,或者static,或者abstract等修饰符,会报错
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }

我们可以看到这一步就是通过反射和注解相关的知识,获取注册对象中 使用 @Subscribe 注解的方法,然后将注解信息(运行线程,是否粘性,事件优先级),方法(Method),事件类型 封装成 SubscriberMethod 保存到 List subscriberMethods 列表中,到这一步我们得到什么呢?

public class XActivity extends Activity {

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(String event) {
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void updateUI2(int event) {
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void updateUI3(Object event) {
    }
}

分析点2

	for (SubscriberMethod subscriberMethod : subscriberMethods) {
		subscribe(subscriber, subscriberMethod);//遍历注解方法,订阅到当前对象 
	}

   //绑定 SubscriberMethod 到 当前对象 
   private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {

		/**
	     * 1.根据注解方法中的参数类型(event)作为key,保存所有参数是 event 的注解方法 的封装对象(包含注解方法所在的类)
	     * 例如:Activity1中存在注解方法 method1(String msg),method2(String msg) 那么Activity1和method1会打包成一个对象保存,Activity1和method2又会打包一个对象保存
	     * 
	     * map.put("String.class", List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)) );
	     * map.put("Int.class", List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)) );
	     * 备注:这里的注册对象其实是注解方法和
	     */	
		/**
	     * 重点对象
	     * 缓存集合 key = 事件对象类型(event.class),value = 所有参数是 event 的注解方法 的封装对象(包含注解方法所在的类)
	     * 可以理解为对于 String.class 类型的事件,有多个 Activity1,Activity2... 中存在接收的方法 (可以结合广播理解,一个 action,可以有多个广播接收器能够接收)
	     */	
		private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

        Class<?> eventType = subscriberMethod.eventType;//获取事件对象类型,也就是注解方法的参数类型
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//构建新的注册对象(理解为封装后的activity&Method对象)
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//根据事件对象类型为Key,获取缓存中的注册对象列表
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);//如果为空,添加到map
        } 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;
            }
        }

		/**
		 *   步骤1总结
	     * 
	     *   @Subscribe(threadMode = ThreadMode.MAIN)
		 *   public void updateUI(String event) {
		 *   }
		 *   
		 *   到这一步为止,会根据 String.class 作为key 保存所有方法参数为String的封装对象(理解为 List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)))
		 *   有什么作用呢?等下 post(String event) 的时候就可以根据这个 String.class 作为key找到 所有的已经注册的对象,然后挨个调用这些对象中的  @Subscribe 方法
	     */	


		/**
	     * 2.根据当前注册对象(Activity)作为key,保存所有事件类型。形成一个map
	     * map.put("Activity1",List(String.class,Int.class..));
	     * map.put("Activity2",List(String.class,Int.class..));
	     */	
		/**
	     * 重点对象
	     * 缓存集合 key = 当前注册对象,value = 事件对象类型列表 
	     * 可以理解为在 Activity1 中存在多个注解方法,他们的事件类型为 String.class ,Int.class   
	     */	
 		private final Map<Object, List<Class<?>>> typesBySubscriber;

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);//添加事件类型


		/**
		 *   步骤2总结
	     * 
		 *   到这一步为止,会根据当前注册对象 Activity 作为key 保存本类中所有注解方法的事件类型(也是方法参数类型)
		 *   
		 *   有什么作用呢?
		 *   1.用于查询是否已经注册了当前对象 isRegistered(Object subscriber){ return typesBySubscriber.containsKey(subscriber); } 
		 *   2.解绑注册 unregister(Object subscriber) 的时候可以找到所有的事件类型,(结合 subscriptionsByEventType )然后再根据事件找到 已经注册对象的列表,移除当前注册的对象
	     */	



		/**
	     * 3.判断当前注册对象中的注解方法是否为粘性事件,如果粘性事件,从粘性事件缓存中取出粘性事件相关的信息
	     */	
		/**
	     * 重点对象
	     * 缓存集合 key = 事件对象类型,value = Object(事件) 
	     * 粘性事件单独存在一个Map集合中,这也是为什么可以先发送粘性事件,然后在注册接收,因为它存放在缓存map中,只要不清除,它就一直在
	     * map.put("String.class", Object 粘性事件1 );
	     * map.put("String.class", Object 粘性事件2 );
	     * map.put("Int.class",    Object 粘性事件1 );
	     * map.put("Int.class",    Object 粘性事件2 );
	     */	
 		private final Map<Class<?>, Object> stickyEvents;

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                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);//根据事件类型在粘性map中查找粘性事件
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);//调用post事件,调用对应的注解方法,使得注解方法能够接收之前发送的粘性事件
            }
        }
    }

通过分析点2,我们可以知道,注册过程中,就是将获取到的注解方法列表 挨个遍历,然后构造了2个重要的map,将数据保存在map中,需要使用的时候再去取出来。
分析点1和分析点2 构成了 register(Object subscriber) 方法,此方法主要内容
1.获取注册对象中通过 @Subscribe 注解的方法,保存在list列表
2.遍历注解方法列表,逐个绑定到当前对象
2.1 根据注解方法事件对象类型,构建map

class Activity1{
	@Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(String event) {
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void updateUI2(int event) {
    }
}

class Activity2{
	@Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(String event) {
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void updateUI2(int event) {
    }
}

map.put("Stirng.class", List(Subscription(Activity1&updateUI),Subscription(Activity2&updateUI)));
map.put("Int.class",	List(Subscription(Activity1&updateUI2),Subscription(Activity2&updateUI2)));

如上述伪代码,Activity1 和 Activity2 中都使用 @Subscribe 注解接收事件的方法,事件的类型为String,int
那么根据事件对象类型作为 key 保存 map 可以得到:map.put(“Stirng.class”, List(Subscription(Activity1&updateUI),Subscription(Activity2&updateUI))); 表示多个Activity绑定了事件对象类型为 String 的事件。 构建这个map有何作用? 因为后续 post(事件)时要根据事件类型发送给所有已经注册该事件类型的对象(Activity)中的注解方法 (updateUI(String event))
2.2 根据注册对象(Activity)保存当前对象中存在的事件类型,构建map

class Activity1{
	@Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(String event) {
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void updateUI2(int event) {
    }
}

map.put("Activity1", List(String.class,Int.class..));

如上述伪代码,在注册对象(这里假设是Activity)中将所有接收事件的事件类型保存起来,可以得到:map.put(“Activity1”, List(String.class,Int.class…)); 表示 Acticity1 对象中存在多种类型的事件。有何作用?1.用于查询是否已经注册了当前对象 2.为解绑注册,释放资源做支撑(解绑注册后面详细分析)
2.3 如果当前注解方法接收的事件是粘性事件,则根据当前方法的参数类型(也就是事件类型)从粘性事件map缓存中(postSticky时保存)获取粘性事件信息,如果存在则执行当前注解方法(实现延迟响应事件的原理)
可以看到 register() 算是一个重头戏,主要是保存一些数据,为后续post发送事件做一些铺垫作用。那接下来就看看 post 方法的源码


EventBus.getDefault().post(Object event);

发送事件,可以是任意类型的事件

	//发送事件
    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();//根据不同Thread区分保存对象
        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 {
                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<?> eventClass = event.getClass();//事件对象class
        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);//发送事件
        }
        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));//未找到订阅对象,发送NoSubscriberEvent
            }
        }
    }

   //根据事件类型发送找到注册对象,然后逐个发送事件
   private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);//获取注册时添加的注册对象,也就是寻找绑定eventClass的activity集合,可以看到这里依赖于注册方法准备的数据
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {//循环所有注册对象(例如:activity1,activity2..)
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    postToSubscription(subscription, event, postingState.isMainThread);//发送事件到已注册的对象(某个activity)
                    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) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING://与发送事件同一个线程,如果post在主线程,避免耗时操作
                invokeSubscriber(subscription, event);//直接反射调用方法
                break;
            case MAIN://主线程
                if (isMainThread) {//如果post在主线程,直接在主线程中运行,会阻塞发布线程
                    invokeSubscriber(subscription, event);
                } else {//如果post在子线程,则事件排队等待传递,使用handler回调到主线程中 
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED://主线程-排队
				/**
			     * 这里就有点尴尬了,前面根据 ThreadMode 类的解释是:不同于MAIN,此模式事件总是排队等待传递,不会阻塞发布线程
			     * 但这里的实现并不是一定方式队列中。不过源码中官方自己备注了技术上实现不正确,未按照 ThreadMode 定义的思想来实现,所以我们就不管它了
			     */	
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);//事件排队等待传递,不会阻塞发布线程
                } else {
 					// temporary: technically not correct as poster not decoupled from subscriber
					// 临时:技术上不正确,未与post线程分离
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND://后台线程
                if (isMainThread) {//如果post是主线程,则使用单个后台线程按顺序执行
                    backgroundPoster.enqueue(subscription, event);
                } else {//如果post在子线程,则在post所在的线程执行
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC://异步线程,总是使用异步线程执行,通过线程池管理异步线程,不会阻塞发布线程和主线程
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

	//最终执行方法,通过反射调用 method.invoke(方法所在对象,方法参数)
   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);
        }
    }

post 方法代码很简单,跟着注释走主要路线就行,首先通过事件类型,找到已经注册的列表,(注册列表在每次注册的时候添加),找到注册列表之后挨个发送当前事件,怎么发送当前事件?找到注册对象的目标method,根据method指定的运行线程,按需要做一些线程切换的操作,然后通过反射调用 method.invoke(方法所在对象,方法参数),就这么简单。
再看看发送粘性事件是怎么处理的

  //发送粘性事件
  public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);//将粘性事件保存到缓存map中
        }
        // 调用post方法
        post(event);
    }

粘性事件和普通事件相比,就多了一步将粘性事件保存到缓存 map 中,原来粘性事件的原理这么简单,发送的时候保存到缓存map中,延时(需要时)再取,实现了可以先发送事件,后注册的效果。


EventBus.getDefault().unregister(Object subscriber);

    //解绑注册,释放资源等
    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 {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

	//根据事件类型解绑已注册对象
 	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--;
                }
            }
        }
    }

首先通过当前对象找到本类中所有的事件类型,再根据某个事件类型找到已经注册该事件的对象列表(如:activity1,activity2…),然后根据比较当前对象是否存在列表中,如果存在,从列表中移除,释放资源
以上便是EventBus的源码解析,结合注释,相信能够看懂它的原理思想,由于分析的时候需要抓住主线不向外扩散,忽略了一些代码,看客最好根据文章打开源码对照着看看,加深印象。文章基于 EventBus 3.1.1


为什么EventBus传递大数据时不会崩溃?

Intent 方式实际上底层parcel对象在不同activity直接传递过程中保存在一个叫做“ Binder transaction buffe ”的缓冲区,并且这个缓冲区大小有限制,不能超过1M。
EventBus 不存在将数据放在什么缓冲区中,普通事件直接拿到事件对象,找到需要调用的方法直接调用即可,简单的方法参数传递; 而粘性事件,将数据缓存在内存中,保存在map,除非是内存爆炸,不然是没有大小限制的说法。因此说EventBus可以传递大数据

EventBus如何指定接收事件方法运行的线程?

EventBus 通过注解的方式指定接收事件的运行线程,在注册的时候将注解信息保存起来,当post事件的时候拿到注册时保存的注解信息(运行线程),通过不同的 ThreadMode 做不同的处理,如开启工作线程执行接收事件的方法,或者通过handler方式将事件运行在主线程中,以此达到指定线程运行方法的目的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值