0

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.

JohnRock
  • 6,795
  • 15
  • 52
  • 61

1 Answers1

0
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.

Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91
  • Your answer worked for me. I am curious, however, how your suggestion of multiple event busses would work. How would an activity subscribe to events from multiple eventBuses? Would you inject multiple eventbuses into the activity? How would a broadcast receiver specify which eventBus was to be injected? – JohnRock May 07 '14 at 14:59
  • @TheLizardKing yes I see what you mean. You need to make sure that the `EventBus` instance is shared between the listener (or subscriber) and the event poster (broadcast receiver), so that while there's no global singleton, you still make sure your eventBus is shared by at least two objects, otherwise there's no communication obviously. Well you can use a `Provider` for that. It can be injected itself. See this answer, for example: http://stackoverflow.com/a/18358445/168719 – Konrad Morawski May 08 '14 at 07:11