问大家一个问题:
Activity之间进行通信你现在使用的是什么?
大家第一印象中Activity之间进行通信是否还是:Intent , Handler,EventBus , RxBus ,广播。
如果你还在用上面说的这些,那你的技术还停留在老旧和原始的技术上,现在技术从LiveData中延伸出 LiveDataBus ,用谷歌的原话
从18年谷歌IO大会开始 官方建议:
在Activity与Activity ,Activity与Fragment,Fragment与Fragment之间通信使用LivedataBus。
1、Activity之间进行通信(LiveDataBus)
下面进入代码:
/**
* 这条总线用于把任何类中的数据直接传递到activity或是fragment上
*/
class LiveDataBus private constructor() {
//存放订阅者
private val bus: MutableMap<String, MutableLiveData<Any>>
init {
bus = HashMap()
}
//注册订阅者,(存入map)
@Synchronized
fun <T> with(key: String, type: Class<T>?): MutableLiveData<T> {
if (!bus.containsKey(key)) {
bus[key] = MutableLiveData()
}
return bus[key] as MutableLiveData<T>
}
companion object {
val instance = LiveDataBus()
}
}
使用:
发送
LiveDataBus.instance.with("first", String::class.java).postValue("数据111")
接收
LiveDataBus.instance.with("first", String::class.java).observe(this) {
Log.e("TAG", "接收到数据为:$it")
}
LiveDataBus 与 EventBus、RxBus的 比较
LiveDataBus 与 EventBus 的比较:
LiveDataBus的实现及其简单,相对EventBus复杂的实现,LiveDataBus只需要一个类就可以实
LiveDataBus 与 RxBus 的比较:
LiveDataBus可以减小APK包的大小 并且 依赖支持也更好。因为 LiveDataBus只依赖Android官方组件LiveData,本身实现只一个类。而RxBus需要依赖RxJava和RxAndroid。
最后还有一点 LiveDataBus具有生命周期感知。
在Android系统中使用调用者不需要调用反注册,相比EventBus和RxBus使用更为方便,并且没有内存泄漏风险。
2、通信之FlowBus
请看本人另外一篇文章:
android——消息总线(Eventbus、FlowBus)_android 总线_wy313622821的博客-CSDN博客