1

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 ?

Zulqurnain Jutt
  • 1,083
  • 3
  • 15
  • 41

2 Answers2

2

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

Jordy Langen
  • 3,591
  • 4
  • 23
  • 32
1

yes, you can convert Service for using Observables by using PublishSubject . Just return it as observable by subject.asObservable() and pass it new event from onEvent() method by subject.onNext(). Use Service binding to bind your Service to Activity, and , whithing binding interface, return references to your subjects as observables.

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");
Alex Shutov
  • 3,217
  • 2
  • 13
  • 11