Skip to content

Instantly share code, notes, and snippets.

@electrolobzik
Created March 28, 2017 10:16
Show Gist options
  • Save electrolobzik/b59bef48e3b76fc5b5361ad47fb677cd to your computer and use it in GitHub Desktop.
Save electrolobzik/b59bef48e3b76fc5b5361ad47fb677cd to your computer and use it in GitHub Desktop.
Event bus implementation with RxJava and RxRelay (https://github.com/JakeWharton/RxRelay) with API similar to https://github.com/greenrobot/EventBus
/**
* Created with Android Studio
* User: electrolobzik [email protected]
* Date: 27/03/2017
* Time: 22:05
*
* Event bus implementation with RxJava and RxRelay (https://github.com/JakeWharton/RxRelay) with API similar to https://github.com/greenrobot/EventBus
*/
class RxBus<T> {
var stickyEvent: T? = null
private val publishRelay: PublishRelay<T> = PublishRelay.create<T>()
fun <E : T> post(event: E) {
publishRelay.call(event)
}
fun <E : T> postSticky(event: E) {
post(event)
stickyEvent = event
}
fun observeEvents(): Observable<T> {
return publishRelay
}
fun observeEventsSticky(): Observable<T> {
val result: Observable<T>
val stickyEvent = stickyEvent
if (stickyEvent != null) {
result = Observable.just(stickyEvent).mergeWith(publishRelay)
} else {
result = publishRelay
}
return result
}
fun <E : T> observeEvents(eventClass: Class<E>): Observable<E> {
return observeEvents().ofType(eventClass) //pass only events of specified type, filter all other
}
fun <E : T> observeEventsSticky(eventClass: Class<E>): Observable<E> {
return observeEventsSticky().ofType(eventClass)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment