fengzhizi715 / PubSub

使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PubSub

@Tony沈哲 on weibo License

使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus

下载

将它添加到项目的 root build.gradle 中:

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

然后在项目或者在 module 中添加:

implementation 'com.github.fengzhizi715.PubSub:core:v1.1.0'

Feature

  • 支持事件发布和订阅
  • 支持 Sticky Event/Retained Event
  • 线程安全,可以在任何线程中发布/订阅事件,支持使用指定的线程进行事件订阅
  • 支持延时发送事件
  • 支持事件发送的异常处理

Usage

  1. 定义 EventBus

可以定义全局的 EventBus 或者定义多个 EventBus

val eventBus: Broker by lazy {
    Broker(Dispatchers.IO)
}
  1. 定义事件
class XXXEvent
  1. 发送事件
eventBus.publish(XXXEvent())

发送 Sticky Event/Retained Event

eventBus.publish(XXXEvent(),true)

延时发送事件

GlobalScope.launch {
    eventBus.publish(XXXEvent(),false,2000)
}
  1. 订阅事件
runBlocking{
    eventBus.subscribe<XXXEvent>("subscriber name", this, Dispatchers.IO) {
        ......
    }
}

订阅 Sticky Event/Retained Event

runBlocking{
    eventBus.subscribe<XXXEvent>("subscriber name", this, Dispatchers.IO,true) {
        ......
    }
}
  1. 取消订阅
eventBus.unsubscribe("subscriber name")

取消所有的订阅

eventBus.unsubscribeAll()
  1. 异常处理
runBlocking {
    eventBus.subscribe<ExceptionEvent>("subscriber name", this, Dispatchers.IO) { event ->
        event.error.printStackTrace()
        ......
    }
}

About

使用 Kotlin Coroutines 实现的 Local Pub/Sub、Event Bus、Message Bus

License:Apache License 2.0


Languages

Language:Kotlin 100.0%