我目前正在使用EventBus
将数据从FirebaseMessagingService onMessageReceived
传输到MainActivity,但随着复杂性的继续,这会变得棘手,如果我收到多个通知会怎么样?另一方面,
由于EventBus,数据传输耗费了1个额外级别和2个样板功能。
问题是如何使用Rxjava将数据从FirebaseMessagingService传输到Activity,有没有办法将整个服务转换为某些可观察对象?
答案 0 :(得分:1)
是的,您可以使用PublishSubject转换Service以使用Observable。只需将其作为可观察对象返回 subject.asObservable()并从onEvent()方法传递新事件 subject.onNext()。 使用服务绑定将您的服务绑定到Activity,并使用绑定接口将对象的引用作为可观察对象返回。
B contains A
答案 1 :(得分:1)
您仍然需要Service
才能收到通知。但是,您可以使用PublishSubject
发布如下项目:
class NotificationsManager {
private static PublishSubject<Notification> notificationPublisher;
public PublishSubject<Notification> getPublisher() {
if (notificationPublisher == null) {
notificationPublisher = PublishSubject.create();
}
return notificationPublisher;
}
public Observable<Notification> getNotificationObservable() {
return getPublisher().asObservable();
}
}
class FirebaseMessagingService {
private PublishSubject<Notification> notificationPublisher;
public void create() {
notificationPublisher = NotificationsManager.getPublisher()
}
public void dataReceived(Notification notification) {
notificationPublisher.onNext(notification)
}
}
class MyActivity {
private Observable<Notification> notificationObservable;
public void onCreate(Bundle bundle) {
notificationObservable = NotificationsManager.getNotificationObservable()
notificationObservable.subscribe(...)
}
}
编辑:扩展了示例。请注意,这不是最好的方法,只是一个例子