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

强颜欢笑 提交于 2019-12-12 19:15:43

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/38183848/eventbus-on-android-how-to-implement-dynamic-queues-vs-class-based-event-subsc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!