Android上的EventBus:如何实现动态队列与基于类的事件订阅? [英] EventBus on Android: how to implement dynamic queues vs. class-based event subscription?

查看:276
本文介绍了Android上的EventBus:如何实现动态队列与基于类的事件订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用EventBus(由Greenrobot或任何其他公司提供)在Android应用程序的组件之间进行通信.

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.

这是我需要完成的:我的应用程序需要向多个系统发送命令(例如,"Hello!"):1、2,...N.所有命令的结构均相同

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.

因此,发布者将能够发送到"command/1","command/2",...","command/N"队列是有意义的,但是要求每个系统都定义一个"CommandN"类.

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?

预先感谢

最大

推荐答案

我建议的一种简单方法是在事件类中添加变量作为命令.

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.

此处是 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.
  }
}

这篇关于Android上的EventBus:如何实现动态队列与基于类的事件订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆