Search code examples
androidroboguice

How to inject a google guava eventbus as a global singleton using Roboguice in android?


How do I set up Roboguice to use the same instance of eventbus when injected into my Activities and Broadcast Receivers like this:

@Inject EventBus eventBus;

That is to say: As far as I understand, the event bus must be a global process singleton in order for events posted in Broadcast Receivers to be subscribed to in my activities. Currently, however, I seem to be getting a separate event bus for each injection.


Solution

  • final EventBus bus = new EventBus();
    

    in your module, and

    bind(EventBus.class).toInstance(bus); // or an otherwise exposed singleton
    

    in its configure method should do the trick.

    As far as I understand, the event bus must be a global process singleton in order for events posted in Broadcast Receivers to be subscribed to in my activities

    Not necessarily.

    All it takes is to register the activity (as a listener) in the event bus owned by the broadcast receiver.

    There can be many event bus instances, each representing a separate channel of event-based communication.

    Or there could be one event bus per each broadcast receiver, and even several activities simultaneously subscribed to the events it posts.

    In and of itself, there is no requirement to use a singleton here, and I'd actually be inclined to speak against it if that design choice has no good justification behind it.