https://github.com/fengzhizi715/pubsub
使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus
https://github.com/fengzhizi715/pubsub
Last synced: 7 days ago
JSON representation
使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus
- Host: GitHub
- URL: https://github.com/fengzhizi715/pubsub
- Owner: fengzhizi715
- License: apache-2.0
- Created: 2021-12-29T05:40:19.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-04-10T06:30:57.000Z (about 1 year ago)
- Last Synced: 2025-04-01T10:41:40.202Z (27 days ago)
- Language: Kotlin
- Homepage:
- Size: 80.1 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# PubSub
[](http://www.weibo.com/fengzhizi715)
[](https://www.apache.org/licenses/LICENSE-2.0.html)
[](https://jitpack.io/#fengzhizi715/PubSub)使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus
## 下载
将它添加到项目的 root build.gradle 中:
```groovy
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```然后在项目或者在 module 中添加:
```groovy
implementation 'com.github.fengzhizi715.PubSub:core:v1.1.0'
```## Feature
* 支持事件发布和订阅
* 支持 Sticky Event/Retained Event
* 线程安全,可以在任何线程中发布/订阅事件,支持使用指定的线程进行事件订阅
* 支持延时发送事件
* 支持事件发送的异常处理## Usage
1. 定义 EventBus
可以定义全局的 EventBus 或者定义多个 EventBus
```kotlin
val eventBus: Broker by lazy {
Broker(Dispatchers.IO)
}
```2. 定义事件
```kotlin
class XXXEvent
```3. 发送事件
```kotlin
eventBus.publish(XXXEvent())
```发送 Sticky Event/Retained Event
```kotlin
eventBus.publish(XXXEvent(),true)
```延时发送事件
```kotlin
GlobalScope.launch {
eventBus.publish(XXXEvent(),false,2000)
}
```4. 订阅事件
```kotlin
runBlocking{
eventBus.subscribe("subscriber name", this, Dispatchers.IO) {
......
}
}
```订阅 Sticky Event/Retained Event
```kotlin
runBlocking{
eventBus.subscribe("subscriber name", this, Dispatchers.IO,true) {
......
}
}
```5. 取消订阅
```kotlin
eventBus.unsubscribe("subscriber name")
```取消所有的订阅
```kotlin
eventBus.unsubscribeAll()
```6. 异常处理
```kotlin
runBlocking {
eventBus.subscribe("subscriber name", this, Dispatchers.IO) { event ->
event.error.printStackTrace()
......
}
}
```