0

我目前只是EventBus用来将数据从 FirebaseMessagingService 传输onMessageReceived到 MainActivity ,但是随着复杂性的增加,这变得越来越棘手,如果我收到多个通知怎么办?另一方面,

由于 EventBus,数据传输需要 1 个额外的类和 2 个样板函数。

所以问题是如何使用 Rxjava 将数据从 FirebaseMessagingService 传输到 Activity ,有没有办法将整个服务转换为一些 observables?

4

2 回答 2

2

您仍然需要Service接收通知。但是,您可以使用 aPublishSubject来发布这样的项目:

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(...)
    }
}

编辑:扩展示例。请注意,这不是最好的方法,只是一个例子

于 2016-11-14T12:51:03.593 回答
1

是的,您可以使用 PublishSubject 将 Service 转换为使用 Observables。只需通过 subject.asObservable() 将其作为 observable 返回,并通过 subject.onNext() 从 onEvent() 方法传递新事件。使用服务绑定将您的服务绑定到活动,并且,通过绑定接口,将对您的主题的引用作为可观察对象返回。

PublishSubject<String> eventPipe = PublishSubject.create();

        Observable<String> pipe = eventPipe.observeOn(Schedulers.computation()).asObservable();
        // susbcribe to that source
        Subscription s =  pipe.subscribe(value -> Log.i(LOG_TAG, "Value received: " + value));

        // give next value to source (use it from onEvent())
        eventPipe.onNext("123");

        // stop receiving events (when you disconnect from Service)
        if (s != null && !s.isUnsubscribed()){
            s.unsubscribe();
            s = null;
        }

        // we're disconnected, nothing will be printed out
        eventPipe.onNext("321");
于 2016-11-14T12:49:08.607 回答