Created
December 3, 2018 21:18
-
-
Save wesleybliss/427be5c801669b96d22dc9647f641129 to your computer and use it in GitHub Desktop.
Kotlin event bus example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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