初次探索,可能会有很多问题,需要慢慢修改!
依赖第三方库:Rxjava和RxAndroid
compile'io.reactivex:rxjava:1.1.5'
compile 'io.reactivex:rxandroid:1.2.0'
/** * 通过rxjava、rxandroid实现EventBus功能 * 使用方式: * 1、注册时返回一个Observable<T>,register(T), * 2、注销时的参数为(T,Observable), * 3、订阅:observable.subscribe(new Action1<T>() { * @Override public void call(T t) { * } * }); * */ public class RxBus { private static final String TAG = RxBus.class.getSimpleName(); private HashMap<Object, List<Subject>> maps = new HashMap<>(); private static RxBus instance; private RxBus() { } public static RxBus getRxBus() { if (instance == null) { synchronized (RxBus.class) { instance = new RxBus(); } } return instance; } @SuppressWarnings("unchecked") public <T> Observable<T> register(@NonNull Class<T> clazz) { Log.i(TAG, "register:" + clazz.getSimpleName()); return this.register(clazz.getSimpleName(), clazz); } @SuppressWarnings("unchecked") public <T> Observable<T> register(@NonNull Object tag, @NonNull Class<T> clazz) { List<Subject> subjects = maps.get(tag); if (subjects == null) { subjects = new ArrayList<>(); maps.put(tag, subjects); } Subject<T, T> subject = PublishSubject.<T>create(); subjects.add(subject); return subject; } /** * @param tag 注册时使用的tag,当注册时参数只有一个类名时,tag为类的名字 * @param observable */ @SuppressWarnings("unchecked") public void unregister(@NonNull Object tag, @NonNull Observable observable) { List<Subject> subjects = maps.get(tag); if (subjects != null) { subjects.remove(observable); if (subjects.isEmpty()) { maps.remove(subjects); } } } @SuppressWarnings("unchecked") public void post(@Nullable Object obj) { Log.i(TAG, "post:" + obj.getClass().getSimpleName()); this.post(obj.getClass().getSimpleName(), obj); } @SuppressWarnings("unchecked") public void post(@NonNull Object tag, @NonNull Object obj) { List<Subject> subjects = maps.get(tag); if (subjects != null && !subjects.isEmpty()) { for (Subject s : subjects) { s.onNext(obj); } } } }