我想使用 RxJava就像我会使用 Guava 的 EventBus 或 Otto,但我不知道如何让它以这种方式运行。
场景是这样的:假设我想在我的 Android 应用程序中有一个按钮,每次按下按钮时我都希望 RxJava 通过我的 Observable 发出一个事件。在我看来,我必须在获得事件后让服务重新注册
,并且该 Activity 还需要创建一个新的可观察对象。
如果我说的话
Observable.from(x)
在我看来我需要为每个事件都这样做,但这会创建一个需要再次注册的新可观察对象。我肯定遗漏了什么。
最佳答案
你可能想做这样的事情(来自 rx.subjects.PublishSubject):
PublishSubject<Object> subject = PublishSubject.create();
// observer1 will receive all onNext and onCompleted events
subject.subscribe(observer1);
subject.onNext("one");
subject.onNext("two");
// observer2 will only receive "three" and onCompleted
subject.subscribe(observer2);
subject.onNext("three");
subject.onCompleted();
如果您可以将 Subject 接口(interface)注入(inject)到 Service 中,将 PublishSubject 注入(inject)到 Activity 中(或者反之亦然,具体取决于您在做什么),您就可以很好地分离关注点。
关于java - RxJava 和 Android 上的随机零星事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19266834/