概述
用途
用安卓jetpack提供的flow封装一个事件总线。支持黏性非粘性等一系列事件。
对比
RxBus:不用引入RxJava库,安卓端即可
LiveData:LiveData不知道谁发明的封装事件总线,反射源码不说,LiveData就不是用来干这事的。
Flow:代码简洁,Android封装
代码(给个赞,不要伸手党)
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.asLiveData
import com.sweet.framework.eventbus.core.EmptyMessage
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import java.util.concurrent.ConcurrentHashMap
object SweetFlowBus {
private var events = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()
private var stickyEvents = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()
private fun <T> with(objectKey: Any): MutableSharedFlow<T> {
if (!events.containsKey(objectKey)) {
events[objectKey] = MutableSharedFlow(0, 1, BufferOverflow.DROP_OLDEST)
}
return events[objectKey] as MutableSharedFlow<T>
}
private fun <T> withSticky(objectKey: Any): MutableSharedFlow<T> {
if (!stickyEvents.containsKey(objectKey)) {
stickyEvents[objectKey] = MutableSharedFlow(1, 1, BufferOverflow.DROP_OLDEST)
}
return stickyEvents[objectKey] as MutableSharedFlow<T>
}
fun <T> observe(owner: LifecycleOwner, objectKey: Any, observer: Observer<T>) {
return with<T>(objectKey).asLiveData().observe(owner, observer)
}
fun observe(owner: LifecycleOwner, objectKey: Any, observer: () -> Unit) {
return with<EmptyMessage>(objectKey).asLiveData().observe(owner) {
observer()
}
}
fun <T> observeForever(objectKey: Any, observer: Observer<T>) {
return with<T>(objectKey).asLiveData().observeForever(observer)
}
fun observeForever(objectKey: Any, observer: () -> Unit) {
return with<EmptyMessage>(objectKey).asLiveData().observeForever {
observer()
}
}
fun <T> observeSticky(owner: LifecycleOwner, objectKey: Any, observer: Observer<T>) {
return withSticky<T>(objectKey).asLiveData().observe(owner, observer)
}
fun observeSticky(owner: LifecycleOwner, objectKey: Any, observer: () -> Unit) {
return withSticky<EmptyMessage>(objectKey).asLiveData().observe(owner) {
observer()
}
}
fun <T> observerStickyForever(objectKey: Any, observer: Observer<T>) {
return withSticky<T>(objectKey).asLiveData().observeForever(observer)
}
fun observerStickyForever(objectKey: Any, observer: () -> Unit) {
return withSticky<EmptyMessage>(objectKey).asLiveData().observeForever {
observer()
}
}
fun post(objectKey: Any) {
with<EmptyMessage>(objectKey).tryEmit(EmptyMessage)
}
fun <T> post(objectKey: Any, objectValue: T) {
with<T>(objectKey).tryEmit(objectValue)
}
fun postSticky(objectKey: Any) {
withSticky<EmptyMessage>(objectKey).tryEmit(EmptyMessage)
}
fun <T> postSticky(objectKey: Any, objectValue: T) {
withSticky<T>(objectKey).tryEmit(objectValue)
}
}
最后
就这样吧,再见!
最后
以上就是满意含羞草为你收集整理的Android 用Flow封装一个FlowBus的全部内容,希望文章能够帮你解决Android 用Flow封装一个FlowBus所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复