EventBus for Android,消息总线,基于SharedFlow,具有生命周期感知能力,支持Sticky,支持线程切换,支持延迟发送。

Overview

背景

跨页面通信是一个比较常见的场景,通常我们会选择使用EventBus,但EventBus无法感知声明周期,收到消息就会回调,所以有了LiveData之后很快就有了LiveEventBus。不过它也有缺点,比如不能切换线程。现在SharedFlow稳定了,那是不是也能搞一波?

于是有了FlowEventBus

常用消息总线对比

消息总线 延迟发送 有序接收消息 Sticky 生命周期感知 跨进程/APP 线程分发
EventBus
RxBus
LiveEventBus
FlowEventBus

设计构思

通过学习 从 LiveData 迁移到 Kotlin 数据流 得到思路:

  • SharedFlow作为事件载体 :
    优点:
  • 依托协程轻松切换线程
  • 可以通过replay实现粘性效果
  • 可以被多个观察者订阅
  • 无观察者自动清除事件不会造成积压

结合 Lifecycle 感知生命周期,做到响应时机可控 。

不仅可以全局范围的事件,也可以单页面内的通信而不透传到别的页面,如:Activity内部,Fragment内部通信。

依赖库版本

关键在于 kotlinx-coroutines > 1.4.xlifecycle-runtime-ktx > 2.3.x

API

以下示例中的XEvent均是随意定义的类,只是测试时为了区分事件而定义的名字

事件发送

//全局范围
postEvent(AppScopeEvent("form TestFragment"))

//Fragment 内部范围 
postEvent(fragment,FragmentEvent("form TestFragment"))

//Activity 内部范围
postEvent(requireActivity(),ActivityEvent("form TestFragment"))

事件监听

//接收 Activity Scope事件
observeEvent<ActivityEvent>(scope = requireActivity()) {
    ...
}

//接收 Fragment Scope事件
observeEvent<FragmentEvent>(scope = fragment) {
    ...
}

//接收 App Scope事件
observeEvent<AppScopeEvent> {
    ...
}

Like ObserveForever:

//此时需要指定协程范围
observeEvent<GlobalEvent>(scope = coroutineScope) {
       ...
}

延迟发送

postEvent(CustomEvent(value = "Hello Word"),1000)

线程切换

observeEvent<ActivityEvent>(Dispatchers.IO) {
    ...
}

指定可感知的最小生命状态

observeEvent<ActivityEvent>(minActiveState = Lifecycle.State.DESTROYED) {
   ...
}

以粘性方式监听

observeEvent<GlobalEvent>(isSticky = true) {
   ...
}

移除粘性事件

    removeStickyEvent(StickyEvent::class.java)
    removeStickyEvent(fragment,StickyEvent::class.java)
    removeStickyEvent(activity,StickyEvent::class.java)

原理

以上功能依托于Kotlin协程的SharedFlowLifecycle 因此实现起来非常简单。

  • 粘性事件
MutableSharedFlow<Any>(
    replay = if (isSticky) 1 else 0,
    extraBufferCapacity = Int.MAX_VALUE //避免挂起导致数据发送失败
)
  • 生命周期感知
fun <T> LifecycleOwner.launchWhenStateAtLeast(
    minState: Lifecycle.State,
    block: suspend CoroutineScope.() -> T
) {
    lifecycleScope.launch {
        lifecycle.whenStateAtLeast(minState, block)
    }
}
  • 切换线程 whenStateAtLeast 由于执行的block默认是在主线程,因此需要手动切换线程:
lifecycleOwner.launchWhenStateAtLeast(minState) {
    flow.collect { value ->
        lifecycleOwner.lifecycleScope.launch(dispatcher) {
                onReceived.invoke(value as T)
        }
    }
}
  • 延迟事件
viewModelScope.launch {
    delay(time)
    flow.emit(value)
}
  • 有序分发
    Flow本身就是有序的

  • 全局单例
    使用全局ViewModel,主要是因为有ViewModelScope,可以避免使用GlobalScope,如果想要单页面内部组件通信,那就使用ActivityScope的ViewModel就行了:

object ApplicationScopeViewModelProvider : ViewModelStoreOwner {

    private val eventViewModelStore: ViewModelStore = ViewModelStore()

    override fun getViewModelStore(): ViewModelStore {
        return eventViewModelStore
    }

    private val mApplicationProvider: ViewModelProvider by lazy {
        ViewModelProvider(
            ApplicationScopeViewModelProvider,
            ViewModelProvider.AndroidViewModelFactory.getInstance(EventBusInitializer.application)
        )
    }

    fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        return mApplicationProvider[modelClass]
    }
}

ViewModel内部有2个map,分别是粘性和非粘性:

internal class EventBusViewModel : ViewModel() {

    private val eventFlows: HashMap<String, MutableSharedFlow<Any>> = HashMap()
   
    private val stickyEventFlows: HashMap<String, MutableSharedFlow<Any>> = HashMap()
    ...

}

总结

站在巨人的肩膀上的同时也可以简单了解下原理。不过挺复杂的,需要下点功夫 😄

kotlinx.coroutines.flow

使用

Add it in your root build.gradle at the end of repositories:

allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Step 2. Add the dependency

dependencies {
	        implementation 'com.github.biubiuqiu0:flow-event-bus:0.0.2'
	}

Step 3. Init

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        EventBusInitializer.init(this)
    }
}

License

MIT License

Copyright (c) 2021 Compose-Museum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

You might also like...
AnyChart Android Chart is an amazing data visualization library for easily creating interactive charts in Android apps. It runs on API 19+ (Android 4.4) and features dozens of built-in chart types.
AnyChart Android Chart is an amazing data visualization library for easily creating interactive charts in Android apps. It runs on API 19+ (Android 4.4) and features dozens of built-in chart types.

AnyChart for Android AnyChart Android Charts is an amazing data visualization library for easily creating interactive charts in Android apps. It runs

android-delicious Delicious Android is an Android app which helps you access and save bookmarks via Delicious. It's available over at Google Play.
android-delicious Delicious Android is an Android app which helps you access and save bookmarks via Delicious. It's available over at Google Play.

Delicious Android Delicious Android is an Android app which helps you access and save bookmarks via Delicious. It's available over at Google Play. Fea

Quality-Tools-for-Android 7.5 0.0 L5 Java This is an Android sample app + tests that will be used to work on various project to increase the quality of the Android platform.
Quality-Tools-for-Android 7.5 0.0 L5 Java This is an Android sample app + tests that will be used to work on various project to increase the quality of the Android platform.

Quality Tools for Android This is an Android sample app + tests that will be used to work on various project to increase the quality of the Android pl

BlackDex is an Android unpack tool, it supports Android 5.0~12 and need not rely to any environment. BlackDex can run on any Android mobile phones or emulators, you can unpack APK File in several seconds.
BlackDex is an Android unpack tool, it supports Android 5.0~12 and need not rely to any environment. BlackDex can run on any Android mobile phones or emulators, you can unpack APK File in several seconds.

BlackDex is an Android unpack tool, it supports Android 5.0~12 and need not rely to any environment. BlackDex can run on any Android mobile phones or emulators, you can unpack APK File in several seconds.

Learn Jetpack Compose for Android by Examples. Learn how to use Jetpack Compose for Android App Development. Android’s modern toolkit for building native UI.
Learn Jetpack Compose for Android by Examples. Learn how to use Jetpack Compose for Android App Development. Android’s modern toolkit for building native UI.

Learn Jetpack Compose for Android by Examples. Learn how to use Jetpack Compose for Android App Development. Android’s modern toolkit for building native UI.

Android-application used as an introduction to Android development and Android APIs.
Android-application used as an introduction to Android development and Android APIs.

Android-application used as an introduction to Android development and Android APIs. This application is an implementation of the game Thirty and written in Kotlin.

Starter-Android-Library - Starter Android Library is an Android Project with Modular Architecture.
Starter-Android-Library - Starter Android Library is an Android Project with Modular Architecture.

Starter-Android-Library - Starter Android Library is an Android Project with Modular Architecture.

AndroidIDE - an IDE for Android to develop full featured Android apps on Android smartphones.
AndroidIDE - an IDE for Android to develop full featured Android apps on Android smartphones.

AndroidIDE - an IDE for Android to develop full featured Android apps on Android smartphones.

Android cutout screen support Android P. Android O support huawei, xiaomi, oppo and vivo.

CutoutScreenSupport Android cutout screen support Android P. Android O support huawei, xiaomi, oppo and vivo. Usage whether the mobile phone is cutout

Android Library to rapidly develop attractive and insightful charts in android applications.
Android Library to rapidly develop attractive and insightful charts in android applications.

williamchart Williamchart is an Android Library to rapidly implement attractive and insightful charts in android applications. Note: WilliamChart v3 h

Remoter - An alternative to Android AIDL for Android Remote IPC services using plain java interfaces

Remoter Remoter - An alternative to Android AIDL for Android Remote IPC services using plain java interfaces Remoter makes developing android remote s

An Android library that allows you to easily create applications with slide-in menus. You may use it in your Android apps provided that you cite this project and include the license in your app. Thanks!

SlidingMenu (Play Store Demo) SlidingMenu is an Open Source Android library that allows developers to easily create applications with sliding menus li

Repo of the Open Source Android library : RoboSpice. RoboSpice is a modular android library that makes writing asynchronous long running tasks easy. It is specialized in network requests, supports caching and offers REST requests out-of-the box using extension modules. Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.
Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.

Green Coffee Green Coffee is a library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests using the

Android Maps Extensions is a library extending capabilities of Google Maps Android API v2.

Android Maps Extensions Library extending capabilities of Google Maps Android API v2. While Google Maps Android API v2 is a huge leap forward comapare

Lynx is an Android library created to show a custom view with all the information Android logcat is printing, different traces of different levels will be rendererd to show from log messages to your application exceptions. You can filter this traces, share your logcat to other apps, configure the max number of traces to show or the sampling rate used by the library. Android library used to create an awesome Android UI based on a draggable element similar to the last YouTube graphic component.
Android library used to create an awesome Android UI based on a draggable element similar to the last YouTube graphic component.

Draggable Panel DEPRECATED. This project is not maintained anymore. Draggable Panel is an Android library created to build a draggable user interface

Bubbles for Android is an Android library to provide chat heads capabilities on your apps. With a fast way to integrate with your development.
Bubbles for Android is an Android library to provide chat heads capabilities on your apps. With a fast way to integrate with your development.

Bubbles for Android Bubbles for Android is an Android library to provide chat heads capabilities on your apps. With a fast way to integrate with your

Comments
  • 与生命周期无关的事件回调

    与生命周期无关的事件回调

    App的Lifecycle生命周期其实监听的是Activity的生命周期,您封装的全局App的事件代码其实还是会跟Activity生命周期相关,必须回调onStart才会收到事件。如果想收到全局与生命周期无关的事件,是否可以考虑添加类似下面的封装:

    //监听App Scope 事件,但是不关心Application的生命周期
    @MainThread
    inline fun <reified T> LifecycleOwner.observeEventWithoutAppLifecycle(
        coroutineScope: CoroutineScope = ProcessLifecycleOwner.get().lifecycleScope,
        isSticky: Boolean = false,
        noinline onReceived: (T) -> Unit
    ): Job {
        return observeEvent(
            coroutineScope,
            isSticky,
            onReceived
        )
    }
    

    谢谢

    opened by rainfoam 1
Releases(1.0.1)
Owner
BiuBiuQiu0
BiuBiuQiu0
Eventbus implemented by Flow

FlowBus FlowVersion EventBus Usage Add it in your root build.gradle at the end of repositories

wenchieh 3 Jun 24, 2021
A Simple kotlin first EventBus implementation

EventBus Simple event bus for event-driven programming. Taking advantage of kotlin language features instead of typical reflections Table of Contents

Zarzel K. Shih 4 Oct 14, 2022
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

EventBus EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components decouples event s

Markus Junginger 24.2k Jan 7, 2023
An enhanced Guava-based event bus with emphasis on Android support.

Otto - An event bus by Square An enhanced Guava-based event bus with emphasis on Android support. Otto is an event bus designed to decouple different

Square 5.2k Jan 9, 2023
eventbus-intellij-plugin 3.8 0.0 L1 Java Plugin to navigate between events posted by EventBus.

eventbus-intellij-plugin Plugin to navigate between events posted by EventBus. Post to onEvent and onEvent to Post Install There are two ways. Prefere

Shinnosuke Kugimiya 315 Aug 8, 2022
Dead simple EventBus for Android made with Kotlin and RxJava 2

KBus Super lightweight (13 LOC) and minimalistic (post(), subscribe(), unsubscribe()) EventBus written with idiomatic Kotlin and RxJava 2 KBus in 3 st

Adriel Café 46 Dec 6, 2022
A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lo

Mr.Simple 1.6k Nov 30, 2022
Eventbus implemented by Flow

FlowBus FlowVersion EventBus Usage Add it in your root build.gradle at the end of repositories

wenchieh 3 Jun 24, 2021
Realize EventBus with LiveData

LiveDataBus 增強UnPeek-LiveData,將其包裝成觀察者模式的事件總線 Getting started Add it in your root build.gradle at the end of repositories: allprojects { repositor

JaredDoge 2 Oct 25, 2022
A Simple kotlin first EventBus implementation

EventBus Simple event bus for event-driven programming. Taking advantage of kotlin language features instead of typical reflections Table of Contents

Zarzel K. Shih 4 Oct 14, 2022