Skip to content

Instantly share code, notes, and snippets.

@Hasiy
Created December 25, 2019 06:48
Show Gist options
  • Save Hasiy/4d6fbd34ca41d21a5378455fe69cb68b to your computer and use it in GitHub Desktop.
Save Hasiy/4d6fbd34ca41d21a5378455fe69cb68b to your computer and use it in GitHub Desktop.
RxBus2 - Kotlin
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
/*
* @Author: Hasiy
* @Date: 2019/12/25 - 14 : 37
* @Description: Android
* @Email: Hasiy.jj@gmail.com
*/
class RxBus2 private constructor() {
private val bus: Subject<Any> = PublishSubject.create<Any>().toSerialized()
// toSerialized method made bus thread safe
private object Holder {
val BUS = RxBus2()
}
fun post(obj: Any?) {
if (obj != null) {
bus.onNext(obj)
}
}
fun <T> toObservable(tClass: Class<T>?): Observable<T> {
return bus.ofType(tClass)
}
fun toObservable(): Observable<Any> {
return bus
}
fun hasObservers(): Boolean {
return bus.hasObservers()
}
companion object {
val instance: RxBus2
get() = Holder.BUS
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment