EventBus封装

EventBus封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.example.eventbus.utils

import com.example.gaokao.event.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.meta.SubscriberInfoIndex

/**
*
* @author: xue
* @description EventBus封装
* @date: 2019/7/5
*/
class EventBusUtil {
companion object {
/**
* 使用索引加速
* 建议在Application中使用
*/
fun installIndex(index: SubscriberInfoIndex) {
EventBus.builder().addIndex(index).installDefaultEventBus()
}

/**
* 注册
*/
fun register(subscribe: Any) {
if (!EventBus.getDefault().isRegistered(subscribe)) {
EventBus.getDefault().register(subscribe)
}
}

/**
* 取消注册
*/
fun unregister(subscribe: Any) {
EventBus.getDefault().unregister(subscribe)
}

/**
* 发布一个订阅事件
* 必须先注册,才能接收到发布的事件,有点类似于 startActivityForResult()方法
*/
fun postEvent(event: MessageEvent) {
EventBus.getDefault().post(event)
}

/**
* 发布粘性事件(可以先发布事件,在注册后在接收)
* 粘性事件将最新的信息保存在内存中,取消原始消息,执行最新的消息;
* 只有注册后,才能接收消息,如果没有注册,消息将保留在内存中。
*/
fun postStickyEvent(event: MessageEvent) {
EventBus.getDefault().postSticky(event)
}

/**
* 移除指定的粘性订阅事件
* @param eventType 事件类型
*/
fun <T> removeStickyEvent(eventType: Class<T>) {
var stickyEvent: T = EventBus.getDefault().getStickyEvent(eventType)
if (stickyEvent != null) {
EventBus.getDefault().removeStickyEvent(stickyEvent)
}
}
/**
* 移除指定的粘性订阅事件
* @param eventType 事件类型
*/
fun removeStickyEvent(eventType:Any) {
var stickyEvent = EventBus.getDefault().getStickyEvent(eventType as Class<Any>?)
if (stickyEvent != null) {
EventBus.getDefault().removeStickyEvent(stickyEvent)
}
}

/**
* 移除所有的粘性订阅事件
*/
fun removeAllStickyEvents(){
EventBus.getDefault().removeAllStickyEvents()
}

/**
* 取消事件
* 优先级高的订阅者可以终止事件往下传递
* 只有在事件通过时才能调用(即在事件接收方法中调用)
* @param event 事件
*/
fun cancelEventDelivery(event:Any){
EventBus.getDefault().cancelEventDelivery(event)
}

/**
* 获取 eventbus 单例
*/
fun getEventBus():EventBus{
return EventBus.getDefault()
}
}
}