public class EleBusUtils { private ConcurrentHashMap<Object, CopyOnWriteArrayList<Subject>> subjectMapper = new ConcurrentHashMap<>(); private static volatile EleBusUtils instance; private String FROM; private EleBusUtils() { } public static EleBusUtils getInstance() { EleBusUtils inst = instance; if (inst == null) { synchronized (EleBusUtils.class) { inst = instance; if (inst == null) { inst = new EleBusUtils(); instance = inst; } } } return inst; } /** * 註冊 * */ public <T> Observable<T> register([@NonNull](https://my.oschina.net/u/2981441) Class<T> tag) { CopyOnWriteArrayList<Subject> subjectList = subjectMapper.get(tag); if (null == subjectList) { subjectList = new CopyOnWriteArrayList<>(); subjectMapper.put(tag, subjectList); } Subject<T, T> subject = PublishSubject.create(); subjectList.add(subject); return subject; } /** * 解除註冊 * */ public <T> void unregister([@NonNull](https://my.oschina.net/u/2981441) Class<T> tag, [@NonNull](https://my.oschina.net/u/2981441) Observable observable) { List<Subject> subjects = subjectMapper.get(tag); if (null != subjects) { subjects.remove(observable); if (subjects.isEmpty()) { subjectMapper.remove(tag); } } } public <T> void unregister([@NonNull](https://my.oschina.net/u/2981441) Class<T> tag) { List<Subject> subjects = subjectMapper.get(tag); if (null != subjects) { subjects.clear(); if (subjects.isEmpty()) { subjectMapper.remove(tag); } } } /** * 發送消息 * */ public <T> void post([@NonNull](https://my.oschina.net/u/2981441) Object event) { try { CopyOnWriteArrayList<Subject> subjectList = subjectMapper.get(event.getClass()); if (subjectList != null && !subjectList.isEmpty()) { Iterator<Subject> iterator = subjectList.iterator(); while (iterator.hasNext()) { Subject mSubject = iterator.next(); if (mSubject != null) { mSubject.onNext(event); try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } // for (Subject subject : subjectList) { // subject.onNext(event); // } } } catch (Exception e) { e.printStackTrace(); } } /** * 清除訂閱 */ public void clear() { if (subjectMapper.isEmpty()) { return; } subjectMapper.clear(); } public String getFROM() { return FROM; } public void setFROM(String FROM) { this.FROM = FROM; } }
public class EleEvent {app
public static class PushEvent { public PushInfoModel model; public PushEvent(PushInfoModel pushInfoModel) { this.model = pushInfoModel; } } }