{"id":48680741,"url":"https://github.com/biubiuqiu0/flow-event-bus","last_synced_at":"2026-04-26T20:00:44.021Z","repository":{"id":53745411,"uuid":"386240639","full_name":"biubiuqiu0/flow-event-bus","owner":"biubiuqiu0","description":"EventBus for Android，消息总线，基于SharedFlow，具有生命周期感知能力，支持Sticky，支持线程切换，支持延迟发送。","archived":false,"fork":false,"pushed_at":"2022-03-08T12:27:48.000Z","size":202,"stargazers_count":198,"open_issues_count":3,"forks_count":26,"subscribers_count":3,"default_branch":"master","last_synced_at":"2023-11-07T15:44:15.295Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/biubiuqiu0.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-07-15T09:51:32.000Z","updated_at":"2023-10-09T04:55:52.000Z","dependencies_parsed_at":"2022-09-21T14:53:01.517Z","dependency_job_id":null,"html_url":"https://github.com/biubiuqiu0/flow-event-bus","commit_stats":null,"previous_names":[],"tags_count":4,"template":null,"template_full_name":null,"purl":"pkg:github/biubiuqiu0/flow-event-bus","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/biubiuqiu0%2Fflow-event-bus","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/biubiuqiu0%2Fflow-event-bus/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/biubiuqiu0%2Fflow-event-bus/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/biubiuqiu0%2Fflow-event-bus/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/biubiuqiu0","download_url":"https://codeload.github.com/biubiuqiu0/flow-event-bus/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/biubiuqiu0%2Fflow-event-bus/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32310804,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-26T19:15:34.056Z","status":"ssl_error","status_checked_at":"2026-04-26T19:15:15.467Z","response_time":129,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-11T01:00:36.059Z","updated_at":"2026-04-26T20:00:44.015Z","avatar_url":"https://github.com/biubiuqiu0.png","language":"Kotlin","funding_links":[],"categories":["进程间通信"],"sub_categories":["Spring Cloud框架"],"readme":"# 背景\n跨页面通信是一个比较常见的场景，通常我们会选择使用`EventBus`，但`EventBus`无法感知声明周期，收到消息就会回调，所以有了`LiveData`之后很快就有了`LiveEventBus`。不过它也有缺点，比如不能切换线程。现在`SharedFlow`稳定了，那是不是也能搞一波？  \n\n于是有了`FlowEventBus`\n\n# 常用消息总线对比\n\n消息总线 | 延迟发送 | 有序接收消息 | Sticky | 生命周期感知 | 跨进程/APP | 线程分发\n---|---|---|---|---|---|---\nEventBus | ❌ | ✅ | ✅ | ❌ | ❌ | ✅\nRxBus | ❌ | ✅ | ✅ | ❌ | ❌ | ✅\nLiveEventBus | ✅ | ✅ | ✅ | ✅ | ✅ | ❌\nFlowEventBus| ✅ | ✅ | ✅ | ✅ |❌| ✅ | \n\n\n# 设计构思\n通过学习 [从 LiveData 迁移到 Kotlin 数据流](https://mp.weixin.qq.com/s/o61NDIptP94X4HspKwiR2w)  得到思路：\n- SharedFlow作为事件载体 ：  \n优点：  \n-  依托协程轻松切换线程\n-  可以通过replay实现粘性效果\n-  可以被多个观察者订阅\n-  无观察者自动清除事件不会造成积压\n\n\n结合 Lifecycle 感知生命周期，做到响应时机可控 。\n\n不仅可以全局范围的事件，也可以单页面内的通信而不透传到别的页面，如：Activity内部，Fragment内部通信。\n\n# 依赖库版本\n关键在于 `kotlinx-coroutines \u003e 1.4.x`  和 `lifecycle-runtime-ktx \u003e 2.3.x`\n# API\n\n\u003e 以下示例中的XEvent均是随意定义的类，只是测试时为了区分事件而定义的名字\n## 事件发送\n\n```kotlin\n//全局范围\npostEvent(AppScopeEvent(\"form TestFragment\"))\n\n//Fragment 内部范围 \npostEvent(fragment,FragmentEvent(\"form TestFragment\"))\n\n//Activity 内部范围\npostEvent(requireActivity(),ActivityEvent(\"form TestFragment\"))\n```\n\n## 事件监听\n\n```kotlin\n//接收 Activity Scope事件\nobserveEvent\u003cActivityEvent\u003e(scope = requireActivity()) {\n    ...\n}\n\n//接收 Fragment Scope事件\nobserveEvent\u003cFragmentEvent\u003e(scope = fragment) {\n    ...\n}\n\n//接收 App Scope事件\nobserveEvent\u003cAppScopeEvent\u003e {\n    ...\n}\n\n```\n## Like ObserveForever：\n```kotlin\n//此时需要指定协程范围\nobserveEvent\u003cGlobalEvent\u003e(scope = coroutineScope) {\n       ...\n}\n```\n## 延迟发送\n```kotlin\npostEvent(CustomEvent(value = \"Hello Word\"),1000)\n```\n## 线程切换\n```kotlin\nobserveEvent\u003cActivityEvent\u003e(Dispatchers.IO) {\n    ...\n}\n```\n## 指定可感知的最小生命状态\n```kotlin\nobserveEvent\u003cActivityEvent\u003e(minActiveState = Lifecycle.State.DESTROYED) {\n   ...\n}\n```\n## 以粘性方式监听\n```kotlin\nobserveEvent\u003cGlobalEvent\u003e(isSticky = true) {\n   ...\n}\n```\n## 删除粘性事件\n移除粘性事件实例\n```kotlin\n    removeStickyEvent(StickyEvent::class.java)\n    removeStickyEvent(fragment,StickyEvent::class.java)\n    removeStickyEvent(activity,StickyEvent::class.java)\n```\n## 清除粘性事件\n粘性事件实例还在，但没有了`ReplayCache`,新观察者不会收到回调\n```kotlin\n    clearStickyEvent(GlobalEvent::class.java)\n```\n## 获取事件监听者数量\n```kotlin\n    getEventObserverCount(GlobalEvent::class.java)\n```\n# 原理\n 以上功能依托于Kotlin协程的`SharedFlow`和`Lifecycle` 因此实现起来非常简单。 \n- 粘性事件\n```kotlin\nMutableSharedFlow\u003cAny\u003e(\n    replay = if (isSticky) 1 else 0,\n    extraBufferCapacity = Int.MAX_VALUE //避免挂起导致数据发送失败\n)\n```\n- 生命周期感知\n```kotlin\nfun \u003cT\u003e LifecycleOwner.launchWhenStateAtLeast(\n    minState: Lifecycle.State,\n    block: suspend CoroutineScope.() -\u003e T\n) :Job {\n    lifecycleScope.launch {\n        lifecycle.whenStateAtLeast(minState, block)\n    }\n}\n```\n- 自行取消监听  \n  观察事件方法返回一个`Job` 使用方自行可以自行控制是否还继续监听\n```kotlin\n    val job = observeEvent\u003cEvent\u003e{\n        ...\n    }\n    //取消监听\n    job.cancel()\n```\n\n- 切换线程\n`whenStateAtLeast` 由于执行的`block`默认是在主线程，因此需要手动切换线程：\n```kotlin\nlifecycleOwner.launchWhenStateAtLeast(minState) {\n    flow.collect { value -\u003e\n        lifecycleOwner.lifecycleScope.launch(dispatcher) {\n                onReceived.invoke(value as T)\n        }\n    }\n}\n```\n- 延迟事件\n```kotlin\nviewModelScope.launch {\n    delay(time)\n    flow.emit(value)\n}\n```\n- 有序分发  \n`Flow`本身就是有序的\n\n- 全局单例  \n使用全局`ViewModel`，主要是因为有`ViewModelScope`，可以避免使用`GlobalScope`，如果想要单页面内部组件通信，那就使用ActivityScope的ViewModel就行了：\n\n```kotlin\nobject ApplicationScopeViewModelProvider : ViewModelStoreOwner {\n\n    private val eventViewModelStore: ViewModelStore = ViewModelStore()\n\n    override fun getViewModelStore(): ViewModelStore {\n        return eventViewModelStore\n    }\n\n    private val mApplicationProvider: ViewModelProvider by lazy {\n        ViewModelProvider(\n            ApplicationScopeViewModelProvider,\n            ViewModelProvider.AndroidViewModelFactory.getInstance(EventBusInitializer.application)\n        )\n    }\n\n    fun \u003cT : ViewModel\u003e getApplicationScopeViewModel(modelClass: Class\u003cT\u003e): T {\n        return mApplicationProvider[modelClass]\n    }\n}\n```\n  \n  ViewModel内部有2个`map`，分别是粘性和非粘性：\n\n```kotlin\n\ninternal class EventBusViewModel : ViewModel() {\n\n    private val eventFlows: HashMap\u003cString, MutableSharedFlow\u003cAny\u003e\u003e = HashMap()\n   \n    private val stickyEventFlows: HashMap\u003cString, MutableSharedFlow\u003cAny\u003e\u003e = HashMap()\n    ...\n\n}\n```\n# 总结\n\n站在巨人的肩膀上的同时也可以简单了解下原理。不过挺复杂的，需要下点功夫😄  \n\n[kotlinx.coroutines.flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/index.html)\n\n\n# 使用\nAdd it in your root build.gradle at the end of repositories:\n```\nallprojects {\n\t\trepositories {\n\t\t\t...\n\t\t\tmaven { url 'https://jitpack.io' }\n\t\t}\n\t}\n```\nStep 2. Add the dependency\n```\ndependencies {\n\t        implementation 'com.github.biubiuqiu0:flow-event-bus:1.0.1'\n\t}\n```\n\n  \n  Step 3. Init\n  \n```kotlin\nclass MyApplication: Application() {\n    override fun onCreate() {\n        super.onCreate()\n        EventBusInitializer.init(this)\n    }\n}\n```\n\n\n### License\n```\nMIT License\n\nCopyright (c) 2021 Compose-Museum\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbiubiuqiu0%2Fflow-event-bus","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbiubiuqiu0%2Fflow-event-bus","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbiubiuqiu0%2Fflow-event-bus/lists"}