使用 rxjava 将数据从 FirebaseMessagingService 传输到 Activity

Transfer data from FirebaseMessagingService to Activity using rxjava

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

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

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

是的,您可以使用 PublishSubject 将服务转换为使用 Observables。只是 return 它可以被观察到 subject.asObservable() 并通过 onEvent() 方法将新事件传递给它 subject.onNext()。 使用服务绑定将您的服务绑定到 Activity,并且通过绑定接口,return 将您的主题引用为可观察对象。

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");

您仍然需要 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(...)
    }
}

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