Mr.Z Mr.Z - 26 days ago 11
Android Question

Transfer data from FirebaseMessagingService to Activity using rxjava

I am currently just using

EventBus
to transfer data from FirebaseMessagingService
onMessageReceived
to MainActivity , but this is getting tricky as complexity goes on and what if i get multiple notifications ? on the other hand,

Data transfer is costing 1 extra class and 2 boiler plate function due to EventBus.

So Problem is how to transfer data from FirebaseMessagingService to Activity using Rxjava , and is there any way to convert this whole service to some observables ?

Answer

You would still need to Service to receive the notifcations. However, you could use a PublishSubject to publish items like this:

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

Edit: expanded the example. Please note this is not the best way to do it, just an example