其实之前看过几种事件的分发,包括greenrobot的EventBus,还有rxjava写的事件订阅。前者是写法局限,事件使用太多容易混乱,后者是准备弃用rxjava,仅仅对于使用事件订阅来说太重,于是想着自己写个,满足不是太多的事件订阅。封装不是太多,只是提供一些思路,其实不是太复杂。简单的模仿了rxjava的事件订阅,因为习惯了。
先贴源码
package com.wj.eventbus.wjeventbus;
import android.support.annotation.WorkerThread;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import static android.R.attr.tag;
/**
* 消息分发
*
* @author Admin
* @version 1.0
* @date 2017/6/15
*/
public class WjEventBus {
/**
* 单例
*/
private static volatile WjEventBus wjEventBus;
/**
* 消息推送的集合
*/
private ConcurrentHashMap<EventKey, Object> posts = new ConcurrentHashMap<>();
/**
* 订阅的集合
*/
private ConcurrentHashMap<EventKey, Class<?>> subscribes = new ConcurrentHashMap<>();
/**
* 事件回调的集合
*/
private ConcurrentHashMap<EventKey, EventLister> listener = new ConcurrentHashMap<>();
/**
* 粘性事件的分发暂时缓冲区
*/
private ArrayList<PostObject> stickyEventListers = new ArrayList<>();
private int priority = 0;//优先级默认是0
public long id = 0;//id 递增
private int index = -1;//下标
public static WjEventBus getInit() {
if (wjEventBus == null) {
wjEventBus = new WjEventBus();
}
wjEventBus.id++;
return wjEventBus;
}
/**
* 订阅事件
* @param code
* @param o 事件类型
* @param eventListe
* @return
*/
public WjEventBus subscribe(String code, Class<?> o, EventLister eventListe) {
EventKey eventKey = new EventKey(code, priority, id);
subscribes.put(eventKey, o);
listener.put(eventKey, eventListe);
return wjEventBus;
}