Search code examples
androidevent-busotto

Know if an Object is subcribed to an event in EventBus or Otto library


I am developing some feature in my app where I receive a push notification and if some screens of my app are running make some stuff in them like update some list, put a badge and other things.

Use of push notifications is mandatory, I know that websockets or other similar solutions are better for accomplish this feature but we can't use it due to backend restrictions.

To inform the screen we think in use a Event library like Otto or Eventbus.The point is that we want to show a notification only if no screen receive "the message". To solve this problem we first throught in send back a "ACK" event to the notification receiver to inform it that it must not show the notification.

To not make this, (and here is my question) are there some form in one of this libraries to know if some Object is subscribed to a concrete Event?


Solution

  • It's possible, though you can't get the subscribers directly.

    Otto

    If you subscribe to the DeadEvent, you'll receive it every time there's an event without any subscribers:

    @Subscribe
    public void deadEvent(DeadEvent deadEvent) {
        if (deadEvent.event instanceof MyConcreteEvent) {
            // handle the concrete event
        }
    }
    

    EventBus

    The event used here is NoSubscriberEvent:

    public void onEvent(NoSubscriberEvent event) {
        if (event.originalEvent instanceof MyConcreteEvent) {
            // handle the concrete event
        }
    }