Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple event bus based on Android Architecture Component's LiveData. The code is initially based on Alfonz' LiveBus (https://github.com/petrnohejl/Alfonz/blob/dev/alfonz-arch/src/main/java/org/alfonz/arch/event/LiveBus.java) and was optimized for usage in Kotlin. This class needs Google's SingleLiveEvent (https://github.com/googlesamples/android…
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.Observer
import android.support.annotation.MainThread
import android.support.v4.util.ArrayMap
class LiveEventBus {
private val events: MutableMap<Class<out Any>, SingleLiveEvent<out Any>> =
ArrayMap<Class<out Any>, SingleLiveEvent<out Any>>()
@MainThread
@Suppress("UNCHECKED_CAST")
fun <T : Any> observe(
lifecycleOwner: LifecycleOwner,
eventClass: Class<T>,
eventObserver: (event: T) -> Unit) {
events.getOrPut(eventClass) { SingleLiveEvent<T>() }
.let { it as SingleLiveEvent<T> }
.observe(lifecycleOwner, Observer<T> { event -> event?.let(eventObserver) })
}
@MainThread
inline fun <reified T : Any> observe(
lifecycleOwner: LifecycleOwner,
noinline eventObserver: (event: T) -> Unit) =
observe(lifecycleOwner, T::class.java, eventObserver)
@MainThread
fun <T : Any> removeObservers(lifecycleOwner: LifecycleOwner, eventClass: Class<T>) =
events[eventClass]?.removeObservers(lifecycleOwner)
@MainThread
inline fun <reified T : Any> removeObservers(lifecycleOwner: LifecycleOwner) =
removeObservers(lifecycleOwner, T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T : Any> send(event: T) {
events.getOrPut(event::class.java) { SingleLiveEvent<T>() }
.let { it as SingleLiveEvent<T> }
.value = event
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment