Super lightweight (13 LOC) and minimalistic (post()
, subscribe()
, unsubscribe()
) EventBus written with idiomatic Kotlin and RxJava 2
// With data
data class ShowMessageEvent(val message: String)
// Without data
class OtherEvent
override fun onStart() {
super.onStart()
KBus.subscribe<ShowMessageEvent>(this) {
showMessage(it.message)
}
KBus.subscribe<OtherEvent>(this) {
doSomething()
}
}
override fun onStop() {
super.onStop()
KBus.unsubscribe(this)
}
Where:
- ShowMessageEvent - the event you're subscribing
- this - the subscriber (by default the current Activity/Fragment)
- { showMessage() } - the subscription observer
- it - the event instance
If you want to post events between Activities/Fragments just subscribe in onCreate()
(or onPostCreate()
) and unsubscribe in onDestroy()
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
KBus.subscribe<ShowMessageEvent>(this) {
showMessage(it.message)
}
}
override fun onDestroy() {
super.onDestroy()
KBus.unsubscribe(this)
}
KBus.post(ShowMessageEvent("Hello KBus!"))
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'com.github.adrielcafe:KBus:1.0'
}