当前位置:   article > 正文

RxBus的封装_rxbus封装

rxbus封装

要实现fragment与activity之前的通讯,或者service与activity的通讯,我们可以有好几种方式实现

1、广播

2、回调接口

3、eventBus、RxBus

4、其他

 

 

封装了一下RxBus的使用,废话不多说,直接上源码:

GitHub源码

1、ThreadMode,所执行的线程

  1. public enum ThreadMode {
  2. /**
  3. * current thread
  4. */
  5. CURRENT_THREAD,
  6. /**
  7. * android main thread
  8. */
  9. MAIN,
  10. /**
  11. * new thread
  12. */
  13. NEW_THREAD
  14. }

2、Subscribe,注解

  1. @Documented
  2. @Target(ElementType.METHOD)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. public @interface Subscribe {
  5. int code() default -1;
  6. ThreadMode threadMode() default ThreadMode.CURRENT_THREAD;
  7. }

3、SubscriberMethod,存储订阅者的相关信息,并提供invoke调用

  1. public class SubscriberMethod {
  2. public Method method;
  3. public ThreadMode threadMode;
  4. public Class<?> eventType;
  5. public Object subscriber;
  6. public int code;
  7. public boolean originalIsPrimitive;//原始类型是否为基本类型
  8. public SubscriberMethod(Object subscriber, Method method, Class<?> eventType, int code, ThreadMode threadMode, boolean originalIsPrimitive) {
  9. this.method = method;
  10. this.threadMode = threadMode;
  11. this.eventType = eventType;
  12. this.subscriber = subscriber;
  13. this.code = code;
  14. this.originalIsPrimitive = originalIsPrimitive;
  15. }
  16. /**
  17. * 调用方法
  18. *
  19. * @param o 参数
  20. */
  21. public void invoke(Object o) {
  22. try {
  23. Class[] parameterType = method.getParameterTypes();
  24. if (parameterType != null && parameterType.length == 1) {
  25. method.invoke(subscriber, o);
  26. } else if (parameterType == null || parameterType.length == 0) {
  27. method.invoke(subscriber);
  28. }
  29. } catch (IllegalAccessException e) {
  30. e.printStackTrace();
  31. } catch (InvocationTargetException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }

4、PrimitiveBox,基本类型转换成对象类型

  1. public class PrimitiveBox {
  2. /**
  3. * 装箱
  4. *
  5. * @param target 目标类
  6. * @return 转换后的Class
  7. */
  8. public static Class<?> mantle(final Class<?> target) {
  9. if (boolean.class.equals(target)) {
  10. return Boolean.class;
  11. } else if (char.class.equals(target)) {
  12. return Character.class;
  13. } else if (byte.class.equals(target)) {
  14. return Byte.class;
  15. } else if (short.class.equals(target)) {
  16. return Short.class;
  17. } else if (int.class.equals(target)) {
  18. return Integer.class;
  19. } else if (long.class.equals(target)) {
  20. return Long.class;
  21. } else if (float.class.equals(target)) {
  22. return Float.class;
  23. } else if (double.class.equals(target)) {
  24. return Double.class;
  25. } else {
  26. return target;
  27. }
  28. }
  29. }

5、BusData,默认的事件类型

  1. public class BusData {
  2. String id;
  3. String status;
  4. public BusData() {}
  5. public BusData(String id, String status) {
  6. this.id = id;
  7. this.status = status;
  8. }
  9. public String getId() {
  10. return id;
  11. }
  12. public void setId(String id) {
  13. this.id = id;
  14. }
  15. public String getStatus() {
  16. return status;
  17. }
  18. public void setStatus(String status) {
  19. this.status = status;
  20. }
  21. }

6、RxBus,核心类

  1. public class RxBus {
  2. public static final String TAG = "RxBus_log";
  3. private static volatile RxBus defaultInstance;
  4. /**
  5. * key==》订阅者对象,value==》订阅事件(disposable )
  6. */
  7. private Map<Object, List<Disposable>> subscriptionsByEventType = new HashMap<>();
  8. /**
  9. * key==》订阅者对象,value==》事件类型
  10. * <p>
  11. * value是 根据Key所注解的方法的参数类型确定,默认==》BusData,如:
  12. * <p>
  13. * 注解方法==》a(),则value==》BusData
  14. * 注解方法==》a(String str),则value==》String
  15. */
  16. private Map<Object, List<Class>> eventTypesBySubscriber = new HashMap<>();
  17. /**
  18. * key==》事件类型,value==》订阅者信息
  19. * <p>
  20. * value信息包括:订阅者对象(subscriber), 方法名(method), 事件类型(eventType), 事件code(code), 线程类型(threadMode)
  21. */
  22. private Map<Class, List<SubscriberMethod>> subscriberMethodByEventType = new HashMap<>();
  23. private final Subject<Object> bus;
  24. private RxBus() {
  25. this.bus = PublishSubject.create().toSerialized();
  26. }
  27. public static RxBus getDefault() {
  28. RxBus rxBus = defaultInstance;
  29. if (defaultInstance == null) {
  30. synchronized (RxBus.class) {
  31. rxBus = defaultInstance;
  32. if (defaultInstance == null) {
  33. rxBus = new RxBus();
  34. defaultInstance = rxBus;
  35. }
  36. }
  37. }
  38. return rxBus;
  39. }
  40. /**
  41. * 注册
  42. *
  43. * @param subscriber 订阅者
  44. */
  45. public void register(Object subscriber) {
  46. YLogUtil.logD2Tag(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@注册@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@--订阅者对象", subscriber);
  47. //根据对象获取类
  48. Class<?> subClass = subscriber.getClass();
  49. //获取所有方法名
  50. Method[] methods = subClass.getDeclaredMethods();
  51. for (Method method : methods) {
  52. //判断方法是否存在注解
  53. if (method.isAnnotationPresent(Subscribe.class)) {
  54. //获得参数类型
  55. Class[] parameterType = method.getParameterTypes();
  56. //参数不为空 且参数个数为1
  57. if (parameterType != null && parameterType.length == 1) {
  58. Class eventType = parameterType[0];
  59. executeRegistered(subscriber, method, eventType);
  60. } else if (parameterType == null || parameterType.length == 0) {
  61. Class eventType = BusData.class;
  62. executeRegistered(subscriber, method, eventType);
  63. }
  64. }
  65. }
  66. YLogUtil.logD2Tag(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@注册完成@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@--订阅者对象", subscriber);
  67. }
  68. /**
  69. * 取消注册
  70. *
  71. * @param subscriber 订阅者
  72. */
  73. public void unregister(Object subscriber) {
  74. YLogUtil.logD2Tag(TAG, "###################################取消注册###################################--订阅者对象", subscriber);
  75. //通过订阅者对象,获取对应的事件类型集合
  76. List<Class> subscribedTypes = eventTypesBySubscriber.get(subscriber);
  77. if (subscribedTypes != null) {
  78. for (Class<?> eventType : subscribedTypes) {
  79. unSubscribeByEventType(subscriber);
  80. unSubscribeMethodByEventType(subscriber, eventType);
  81. YLogUtil.logD2Tag(TAG, "执行取消注册--订阅者对象", subscriber, "事件类型", eventType);
  82. }
  83. eventTypesBySubscriber.remove(subscriber);
  84. }
  85. YLogUtil.logD2Tag(TAG, "###################################取消注册完成###############################--订阅者对象", subscriber);
  86. }
  87. /**
  88. * 是否注册
  89. *
  90. * @param subscriber 订阅者
  91. * @return
  92. */
  93. public synchronized boolean isRegistered(Object subscriber) {
  94. boolean isRegistered = eventTypesBySubscriber.containsKey(subscriber);
  95. YLogUtil.logD2Tag(TAG, "************************************判断是否注册******************************--订阅者对象", subscriber, "是?", isRegistered);
  96. return isRegistered;
  97. }
  98. /**
  99. * 执行注册
  100. *
  101. * @param subscriber 订阅者对象
  102. * @param method 方法名
  103. * @param eventType 事件类型
  104. */
  105. private void executeRegistered(Object subscriber, Method method, Class eventType) {
  106. //判断是否为基本类型
  107. boolean isPrimitive = eventType.isPrimitive();
  108. if (isPrimitive) {
  109. YLogUtil.logD2Tag(TAG, "*********基础类型自动装箱---开始*********装箱前类型", eventType);
  110. eventType = PrimitiveBox.mantle(eventType);
  111. YLogUtil.logD2Tag(TAG, "*********基础类型自动装箱---完成*********装箱后类型", eventType);
  112. }
  113. // key==》订阅者对象,value==》事件类型,保存到map里
  114. addEventTypeToMap(subscriber, eventType);
  115. //获取注解
  116. Subscribe sub = method.getAnnotation(Subscribe.class);
  117. int code = sub.code();
  118. ThreadMode threadMode = sub.threadMode();
  119. //key==》事件类型,value==》订阅者信息,保存到map里
  120. SubscriberMethod subscriberMethod = new SubscriberMethod(subscriber, method, eventType, code, threadMode, isPrimitive);
  121. addSubscriberToMap(eventType, subscriberMethod);
  122. //添加到RxJava订阅
  123. addSubscriber(subscriberMethod);
  124. YLogUtil.logD2Tag(TAG, "执行注册---方法:", method, "---事件类型:", eventType);
  125. }
  126. /**
  127. * key==》订阅者对象,value==》事件类型,保存到map里
  128. *
  129. * @param subscriber 订阅者对象
  130. * @param eventType 事件类型
  131. */
  132. private void addEventTypeToMap(Object subscriber, Class eventType) {
  133. List<Class> eventTypes = eventTypesBySubscriber.get(subscriber);
  134. if (eventTypes == null) {
  135. eventTypes = new ArrayList<>();
  136. eventTypesBySubscriber.put(subscriber, eventTypes);
  137. }
  138. if (!eventTypes.contains(eventType)) {
  139. eventTypes.add(eventType);
  140. }
  141. }
  142. /**
  143. * key==》事件类型,value==》订阅者信息,保存到map里
  144. *
  145. * @param eventType 事件类型
  146. * @param subscriberMethod 订阅者信息
  147. */
  148. private void addSubscriberToMap(Class eventType, SubscriberMethod subscriberMethod) {
  149. List<SubscriberMethod> subscriberMethods = subscriberMethodByEventType.get(eventType);
  150. if (subscriberMethods == null) {
  151. subscriberMethods = new ArrayList<>();
  152. subscriberMethodByEventType.put(eventType, subscriberMethods);
  153. }
  154. if (!subscriberMethods.contains(subscriberMethod)) {
  155. subscriberMethods.add(subscriberMethod);
  156. }
  157. }
  158. /**
  159. * 用RxJava添加订阅者
  160. *
  161. * @param subscriberMethod 订阅者信息
  162. */
  163. @SuppressWarnings("unchecked")
  164. private void addSubscriber(final SubscriberMethod subscriberMethod) {
  165. Flowable flowable;
  166. if (subscriberMethod.code == -1) {
  167. flowable = toObservable(subscriberMethod.eventType);
  168. } else {
  169. flowable = toObservable(subscriberMethod.code, subscriberMethod.eventType);
  170. }
  171. Disposable subscription = postToObservable(flowable, subscriberMethod)
  172. .subscribe(new Consumer<Object>() {
  173. @Override
  174. public void accept(Object o) throws Exception {
  175. callEvent(subscriberMethod, o);
  176. }
  177. });
  178. //key==》订阅者对象,value==》订阅事件(disposable )
  179. addSubscriptionToMap(subscriberMethod.subscriber, subscription);
  180. }
  181. /**
  182. * 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
  183. *
  184. * @param eventType 事件类型
  185. * @return return
  186. */
  187. public <T> Flowable<T> toObservable(Class<T> eventType) {
  188. //ofType(class) 指定某个类型的class,过滤属于这个类型的的结果,其它抛弃
  189. return bus.toFlowable(BackpressureStrategy.BUFFER).ofType(eventType);
  190. }
  191. /**
  192. * 根据传递的code和 eventType 类型返回特定类型(eventType)的 被观察者
  193. *
  194. * @param code 事件code
  195. * @param eventType 事件类型
  196. */
  197. private <T> Flowable<T> toObservable(final int code, final Class<T> eventType) {
  198. //ofType(class) 指定某个类型的class,过滤属于这个类型的的结果,其它抛弃
  199. return bus.toFlowable(BackpressureStrategy.BUFFER).ofType(Message.class)
  200. //采用filter()变换操作符
  201. .filter(new Predicate<Message>() {
  202. // 根据test()的返回值 对被观察者发送的事件进行过滤 & 筛选
  203. // a. 返回true,则继续发送
  204. // b. 返回false,则不发送(即过滤)
  205. @Override
  206. public boolean test(Message o) throws Exception {
  207. return o.getCode() == code && eventType.isInstance(o.getObject());
  208. }
  209. // map操作符,Function<Object,Object>,只要类型为Object的子类就可以进行转换
  210. }).map(new Function<Message, Object>() {
  211. @Override
  212. public Object apply(Message o) throws Exception {
  213. return o.getObject();
  214. }
  215. }).cast(eventType);
  216. }
  217. /**
  218. * 用于处理订阅事件在那个线程中执行
  219. *
  220. * @param observable 订阅事件
  221. * @param subscriberMethod 订阅者信息
  222. * @return Observable
  223. */
  224. private Flowable postToObservable(Flowable observable, SubscriberMethod subscriberMethod) {
  225. Scheduler scheduler;
  226. switch (subscriberMethod.threadMode) {
  227. case MAIN:
  228. scheduler = AndroidSchedulers.mainThread();
  229. break;
  230. case NEW_THREAD:
  231. scheduler = Schedulers.newThread();
  232. break;
  233. case CURRENT_THREAD:
  234. scheduler = Schedulers.trampoline();
  235. break;
  236. default:
  237. throw new IllegalStateException("Unknown thread mode: " + subscriberMethod.threadMode);
  238. }
  239. return observable.observeOn(scheduler);
  240. }
  241. /**
  242. * key==》订阅者对象,value==》订阅事件(disposable )
  243. *
  244. * @param subscriber 订阅者对象
  245. * @param disposable 订阅事件
  246. */
  247. private void addSubscriptionToMap(Object subscriber, Disposable disposable) {
  248. List<Disposable> disposables = subscriptionsByEventType.get(subscriber);
  249. if (disposables == null) {
  250. disposables = new ArrayList<>();
  251. subscriptionsByEventType.put(subscriber, disposables);
  252. }
  253. if (!disposables.contains(disposable)) {
  254. disposables.add(disposable);
  255. }
  256. }
  257. /**
  258. * 回调到订阅者的方法中
  259. *
  260. * @param subscriberMethod 订阅者信息
  261. * @param object 事件类型对象
  262. */
  263. private void callEvent(SubscriberMethod subscriberMethod, Object object) {
  264. YLogUtil.logD2Tag(TAG, "执行回调----订阅者对象", subscriberMethod.subscriber, "方法", subscriberMethod.method, "事件类型对象", object);
  265. //因为最终发送的为事件类型对象
  266. //所以需要通过事件类型对象,获取对应的事件类型
  267. Class eventClass = object.getClass();
  268. //通过事件类型,获取订阅者信息
  269. List<SubscriberMethod> subscriberMethodList = subscriberMethodByEventType.get(eventClass);
  270. //判断订阅者信息是否相同,并回调订阅者
  271. if (subscriberMethodList != null && subscriberMethodList.size() > 0) {
  272. for (SubscriberMethod tmpSubscriberMethod : subscriberMethodList) {
  273. if (tmpSubscriberMethod.code == subscriberMethod.code && subscriberMethod.subscriber.equals(tmpSubscriberMethod.subscriber)
  274. && subscriberMethod.method.equals(tmpSubscriberMethod.method)) {
  275. tmpSubscriberMethod.invoke(object);
  276. YLogUtil.logD2Tag(TAG, "回调成功----订阅者对象", subscriberMethod.subscriber, "方法", subscriberMethod.method, "事件类型对象", object);
  277. }
  278. }
  279. }
  280. }
  281. /**
  282. * 移除订阅者对象对应的订阅事件
  283. *
  284. * @param subscriber 订阅者对象
  285. */
  286. private void unSubscribeByEventType(Object subscriber) {
  287. List<Disposable> disposables = subscriptionsByEventType.get(subscriber);
  288. if (disposables != null) {
  289. Iterator<Disposable> iterator = disposables.iterator();
  290. while (iterator.hasNext()) {
  291. Disposable disposable = iterator.next();
  292. if (disposable != null && !disposable.isDisposed()) {
  293. disposable.dispose();
  294. iterator.remove();
  295. }
  296. }
  297. }
  298. }
  299. /**
  300. * 移除订阅者对象对应的订阅者信息
  301. *
  302. * @param subscriber 订阅者对象
  303. * @param eventType 事件类型
  304. */
  305. private void unSubscribeMethodByEventType(Object subscriber, Class eventType) {
  306. //通过事件类型,获取订阅者信息
  307. List<SubscriberMethod> subscriberMethods = subscriberMethodByEventType.get(eventType);
  308. //判断订阅者信息的订阅者对象是否相同
  309. if (subscriberMethods != null) {
  310. Iterator<SubscriberMethod> iterator = subscriberMethods.iterator();
  311. while (iterator.hasNext()) {
  312. SubscriberMethod subscriberMethod = iterator.next();
  313. if (subscriberMethod.subscriber.equals(subscriber)) {
  314. iterator.remove();
  315. }
  316. }
  317. }
  318. }
  319. public void send(int code, Object o) {
  320. Message message = new Message(code, o);
  321. bus.onNext(message);
  322. YLogUtil.logD2Tag(TAG, "发送RxBus", o);
  323. }
  324. public void post(Object o) {
  325. bus.onNext(o);
  326. }
  327. public void send(int code) {
  328. Message message = new Message(code, new BusData());
  329. bus.onNext(message);
  330. YLogUtil.logD2Tag(TAG, "发送RxBus", message.object);
  331. }
  332. private class Message {
  333. private int code;
  334. private Object object;
  335. public Message() {
  336. }
  337. private Message(int code, Object o) {
  338. this.code = code;
  339. this.object = o;
  340. }
  341. private int getCode() {
  342. return code;
  343. }
  344. public void setCode(int code) {
  345. this.code = code;
  346. }
  347. private Object getObject() {
  348. return object;
  349. }
  350. public void setObject(Object object) {
  351. this.object = object;
  352. }
  353. }
  354. }

 

RxBus使用方式

一、注册RxBus:

  1. public class TestActivity extends Activity{
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. RxBus.getDefault().register(this);
  6. }
  7. @SuppressLint("测试1,参数为String类型")
  8. @Subscribe(code = 1001, threadMode = ThreadMode.MAIN)
  9. public void rxBusTest1(String msg) {
  10. }
  11. @SuppressLint("测试2,参数为int基本数据类型")
  12. @Subscribe(code = 1002, threadMode = ThreadMode.MAIN)
  13. public void rxBusTest2(int type) {
  14. }
  15. @SuppressLint("测试3,参数为自定义对象")
  16. @Subscribe(code = 1003, threadMode = ThreadMode.MAIN)
  17. public void rxBusTest3(MsgData msgData) {
  18. }
  19. @SuppressLint("测试4,无参")
  20. @Subscribe(code = 1004, threadMode = ThreadMode.MAIN)
  21. public void rxBusTest4() {
  22. }
  23. @Override
  24. protected void onDestroy() {
  25. super.onDestroy();
  26. RxBus.getDefault().unregister(this);
  27. }
  28. }

二、发送RxBus:

  1. RxBus.getDefault().send(1001,"hihi");
  2. RxBus.getDefault().send(1002,123);
  3. RxBus.getDefault().send(1003,new MsgData(111,"test"));
  4. RxBus.getDefault().send(1004);

 

  1. public class MsgData {
  2. public int code;
  3. public String msg;
  4. public MsgData (int code, String msg) {
  5. this.code = code;
  6. this.msg = msg;
  7. }
  8. }

 

混淆:

  1. #如RxBus所在包名为com.cn.rxbus
  2. #Rxbus混淆
  3. -dontwarn com.cn.rxbus.**
  4. -keep class com.cn.rxbus.** { *;}
  5. -keepattributes *Annotation
  6. -keep @com.cn.rxbus.Subscribe class * {*;}
  7. -keep class * {
  8. @com.cn.rxbus.Subscribe <fields>;
  9. }
  10. -keepclassmembers class * {
  11. @com.cn.rxbus.Subscribe <methods>;
  12. }
  13. #Rxbus混淆end

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/291825
推荐阅读
相关标签
  

闽ICP备14008679号