Skip to content

Instantly share code, notes, and snippets.

@wellingtoncosta
Last active January 24, 2019 14:37
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 wellingtoncosta/d5c0ec6141cdfad049d8cbfed77120c5 to your computer and use it in GitHub Desktop.
Save wellingtoncosta/d5c0ec6141cdfad049d8cbfed77120c5 to your computer and use it in GitHub Desktop.
class RxBus private constructor() {
private val subjects = HashMap<String, PublishSubject<Any>>()
private val subscriptions = HashMap<Any, CompositeDisposable>()
private fun subject(key: String) = subjects.getOrPut(key) { PublishSubject.create() }
private fun disposable(key: Any) = subscriptions.getOrPut(key) { CompositeDisposable() }
fun subscribe(subject: String, owner: Any, action: (Any) -> Unit) {
val disposable = subject(subject).subscribe(action)
disposable(owner).add(disposable)
}
fun unregister(owner: Any) { subscriptions.remove(lifecycle)?.dispose() }
fun publish(subject: String, message: Any) { subject(subject).onNext(message) }
companion object {
val instance by lazy { RxBus() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment