Max
Max

Reputation: 643

EventBus on Android: how to implement dynamic queues vs. class-based event subscription?

I want to use EventBus (by Greenrobot, or any other) for the communication between the components of my Android application.

In all the example, the pub/sub was implemented using a "class" as a "topic", i.e. each subscriber declares the exact class of events it should receive.

I wonder if there is a more dynamic mechanism.

Here is what I need to accomplish: my app needs to send commands (say, "Hello!") to multiple systems: 1, 2, ... N. The structure of the command is the same for all of them.

So, it makes sense that the publisher will be able to send to queues "command/1", "command/2", ...", "command/N" - but it doesn't make sense to require each system to define a "CommandN" class.

Any smart way to accomplish this, while keeping the pub/sub decoupling?

Thanks in advance,

Max

Upvotes: 2

Views: 822

Answers (1)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

A simple way that I recommend is by adding a variable as a command in the event class.

Each subscriber will get the event, but only do something if the command number same with its requirement.

Here sample code for EventBus:

public class CommandEvent{
  private int command;

  public CommandEvent(int command) {
    this.command = command;
  }

  public int getCommand() {
    return command;
  }
}

Then in your each subscriber:

@Subscribe
protected void onMessage(CommandEvent event) {
  // Only do something when it's its command it want.
  if(event.getCommand() = myCommandId) {
    // do something here.
  }
}

Upvotes: 1

Related Questions