您好亲爱的同事,Kotlin爱好者在我的第一篇文章中,我想告诉您一个我专门在Kotlin上编写的有用的库,并且我会积极地支持和开发它。 它称为-KDispatcher。 设计用于在代码组件之间邮寄和订阅通知。 您可以在任何kotlin项目中使用它,无论是Android,Frontend,Backend还是KotlinNative。
主要优点:
- 快速简便的事件订阅
- 调用侦听器功能(回调)的优先级
- 使用Kotlin扩展功能
- 线程安全
因此,要在项目中使用此库,您需要通过Gradle将其连接:
implementation 'com.rasalexman.kdispatcher:kdispatcher:xyz'
或Maven:
<dependency> <groupId>com.rasalexman.kdispatcher</groupId> <artifactId>kdispatcher</artifactId> <version>xyz</version> <type>pom</type> </dependency>
之后,您可以使用两种方式:
1)调用对象方法:
KDispatcher.subscribe(eventName, ::listenerFunction, priority)
其中,eventName是您要订阅的事件的字符串名称; :: listenerFunction-一个具有Notification类型的单个参数的函数,其形式可以是
(Notification<T>)->Unit
包含数据的对象(数据:T)和事件的名称(eventName:字符串)。 最后一个可选参数priority:Int是用于对回调函数的调用进行排序的数字变量,因为您可以一次将多个侦听器签名到一个事件。 要传递事件,您需要调用方法:
KDispatcher.call(eventName:String, data:Any)
您还可以使用以下方法取消订阅不再需要的事件:
KDispatcher.unsubscribe(eventName:String, ::listenerFunction)
一切都非常简单。
2)第二种方法是从IKDispatcher接口实现您的类(这个词肯定不是很好,但我希望每个人都能理解),由于kotlin扩展功能,您可以获得事件框架的所有功能,甚至更多。 下面,我想举一个使用此接口的小例子:
class MainActivity : AppCompatActivity(), IKDispatcher { private val eventListenerOne = this::eventOneHandler //... override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scopeOperation() } private fun scopeOperation() { // subscribe(EVENT_CALL_ONE, 3, eventListenerOne) subscribe(EVENT_CALL_ONE, 1, ::eventListenerTwo) subscribe(EVENT_CALL_ONE, 2, MyClass::eventListenerFour) // call(EVENT_CALL_ONE, "FIRST CALL FROM KDISPATCHER") /** * lambda- */ val eventName = "LAMBDA_EVENT" subscribe<String>(eventName) { notification -> println("LAMBDA_EVENT HAS FIRED with event name ${notification.eventName} and data ${notification.data}") unsubscribe(notification.eventName) } call(eventName, "FIRST CALL CUSTOM LABDA EVENT") } fun eventOneHandler(notification:Notification<Any>) { println("eventOneHandler MY TEST IS COMING event = ${notification.eventName} AND data = ${notification.data}") } }
您可以在链接中找到完整的使用示例
GitHub上的KDispatcher感谢您阅读到最后。 在项目开发过程中收到反馈和帮助,我将感到非常高兴。
享受用真棒KOTLIN语言编写的代码!