事件总线基于发布-订阅,安卓广播(Broadcasts)也是基于此设计模式,可以理解为应用级别的安卓广播。与 LocalBroadcastManager 类似。
使用 RxJava 也能方便的实现事件总线:
compile "io.reactivex.rxjava2:rxjava:2.x.y"
Kotlin >
class RxBus2 {
private val subjects : PublishSubject<Any> = PublishSubject.create()
// 线程安全 // http://blog.csdn.net/cml_blog/article/details/51013343
// private val subject : Subject<Any> = subjects.toSerialized()
fun send(event: Any) {
subjects.onNext(event)
}
fun toObservable() = subjects
fun hasObservers() = subjects.hasObservers()
companion object {
private val bus : RxBus2 = RxBus2()
@Synchronized fun get() = bus
}
}
发送事件:
RxBus2.get().send("RxBus")
接收事件:
val disposable = RxBus2.get().toObservable().subscribe { o -> Timber.e("EVENT:$o") }
取消事件:
if (!disposable.isDisposed) disposable.dispose()
可以使用 CompositeDisposable
取消订阅:
val mDisposables: CompositeDisposable = CompositeDisposable()
mDisposables.clear()
也可使用 RxLifecycle 取消订阅:
myObservable
.bindToLifecycle(myView)
.subscribe { }
compile 'com.trello.rxlifecycle2:rxlifecycle-components:xxx'
compile 'com.trello.rxlifecycle2:rxlifecycle-kotlin:xxx'
Java >
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
/**
* @author <a href="mailto:jaredsburrows@gmail.com">Jared Burrows</a>
*/
public final class RxBus {
private final PublishSubject<Object> bus = PublishSubject.create();
public void send(final Object event) {
bus.onNext(event);
}
public Observable<Object> toObservable() {
return bus;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}