说实话不知为何 EventBus 用得多了有种说不出的的感觉,总觉有点缺陷,同时也想使用一下新鲜的工具,毕竟技多不压身
,但是翻看了作者的github发现居然是2016年底最后一次发布。。。
也就是比较老的工具了,不由得自惭形秽,但是决定的事还是要做的, 如下研究一番。
如题引入Mailbox
使用方式 如下
1:在需要收到通知的类中 加上标注
@OnMailReceived
2:加上atHome后 OnMailReceived 方法才会起作用
atHome
3:这个方法即 有通知也收不到
leave
@OnMailReceived
fun onMailReceived(mail: Mail) {
val aMapLocation = mail.content as AMapLocation
indexinfoParam.city = aMapLocation.city
mainCity?.text = aMapLocation.city
indexinfoParam.coordinate = "${aMapLocation.longitude},${aMapLocation.latitude}"
}
override fun attachView() {
Mailbox.getInstance().atHome(this)
}
override fun detachView() {
Mailbox.getInstance().leave(this) }
如下为 调用方法 参数clazz 为需要回传的类 结合上面的atHome方法 在需要的时候即可实时回调
ShopApp.instance.toGetAmapLocation(this)
var amapLocation: AMapLocation? = null
fun toGetAmapLocation(clazz: Any) {
if (amapLocation != null) { Mailbox.getInstance().post(Mail(amapLocation, calzz::class.java))
} else {
mLocationClient?.startLocation()
}
}
同一个通知发送不同意图时: is方法 即可判断意图 类似于EvenBus 的 自定义Event类
@OnMailReceived
fun onMailReceived(mail: Mail) {
if (mail.content is IndexChangeEvent) {
when ((mail.content as IndexChangeEvent).index) {
2 -> {
mPresenter.intervalRange()
}
else -> {
mPresenter.stopIntervalRange()
}
}
}
}
相同意图时:判断来自不同的类通知
@OnMailReceived
fun onMailReceived(mail: Mail) {
if (MainFragment::class.java.simpleName == mail.from?.simpleName) {
val tparr = mail.content as Tparr
nearbyParam.class_id = tparr.class_id
nearbyParam.class_name = tparr.class_name
if (isViewPrepared && hasFetchData) {
around_type_choice?.text = tparr.class_name
onRefresh()
}
} else {
val aMapLocation = mail.content as AMapLocation
change_location?.text = aMapLocation.street
nearbyParam.city = aMapLocation.city
nearbyParam.street = aMapLocation.street
nearbyParam.coordinate = "${aMapLocation.longitude},${aMapLocation.latitude}"
onRefresh()
}
}