Skip to content

Instantly share code, notes, and snippets.

@qq157755587
Created December 31, 2015 02:26
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 qq157755587/0ccab329dfe4a6d18dca to your computer and use it in GitHub Desktop.
Save qq157755587/0ccab329dfe4a6d18dca to your computer and use it in GitHub Desktop.
RxJava实现的EventBus
open class BaseActivity: AppCompatActivity() {
private val subscriptions = CompositeSubscription()
override fun onStart() {
super.onStart()
subscriptions.add(RxBus.toObserverable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onRxBusEvent(it)})
subscriptions.add(RxBus.toStickyObserverable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onRxBusStickyEvent(it) })
}
override fun onStop() {
super.onStop()
subscriptions.clear()
}
override fun onDestroy() {
super.onDestroy()
subscriptions.unsubscribe()
}
protected open fun onRxBusEvent(event: Any) {
}
protected open fun onRxBusStickyEvent(event: Any) {
}
}
object RxBus {
private val bus = SerializedSubject<Any, Any>(PublishSubject.create())
private val stickyBus = SerializedSubject<Any, Any>(ReplaySubject.create(1))
fun send(event: Any) = bus.onNext(event)
fun sendSticky(event: Any) = stickyBus.onNext(event)
fun toObserverable(): Observable<Any> = bus
fun toStickyObserverable(): Observable<Any> = stickyBus
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment