Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created December 3, 2018 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleybliss/427be5c801669b96d22dc9647f641129 to your computer and use it in GitHub Desktop.
Save wesleybliss/427be5c801669b96d22dc9647f641129 to your computer and use it in GitHub Desktop.
Kotlin event bus example
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
/**
* Created by adrielcafe on 20/12/17.
*/
object KBus {
val disposables = mutableMapOf<Any, CompositeDisposable>()
val publishSubject = PublishSubject.create<Any>()!!
inline fun <reified T : Any> subscribe(subscriber: Any, noinline consumer: (T) -> Unit) {
val observer = publishSubject.ofType(T::class.java).subscribe(consumer)
val disposable = disposables[subscriber] ?: CompositeDisposable().apply { disposables[subscriber] = this }
disposable.add(observer)
}
fun unsubscribe(subscriber: Any) {
disposables[subscriber]?.clear()
disposables.remove(subscriber)
}
fun post(event: Any) = publishSubject.onNext(event)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment