KBus

General

Category
Free
Tag
Event Buses
License
MIT License
Min SDK
9 (Android 2.3–2.3.2 Gingerbread)
Registered
Dec 21, 2017
Favorites
3
Link
https://github.com/adrielcafe/KBus
See also
RxBus
RXBus
IPC EventBus
RxBus2
GWSRxBus

Additional

Language
Kotlin
Version
1.0 (Dec 21, 2017)
Created
Dec 21, 2017
Updated
Feb 6, 2018
Owner
Adriel Café (adrielcafe)
Contributor
Adriel Café (adrielcafe)
1
Activity
Badge
Generate
Download
Source code

Advertisement

KBus

Super lightweight (13 LOC) and minimalistic (post(), subscribe(), unsubscribe()) EventBus written with idiomatic Kotlin and RxJava 2

KBus in 3 steps

1. Define your events

// With data
data class ShowMessageEvent(val message: String)

// Without data
class OtherEvent

2. Add subscribers

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

Sticky events

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)
}

3. Post events

KBus.post(ShowMessageEvent("Hello KBus!"))

Add KBus to your project

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
    implementation 'com.github.adrielcafe:KBus:1.0'
}