java - 如何在android中发送事件让我们可以选择订阅者?

标签 java android publish-subscribe greenrobot-eventbus

我有 4 个类(class)都订阅了事件消息。我只想向其中 2 个类发送事件消息。 EventBus 正在向所有 4 个类发送事件。

最佳答案

This use case can be very easily solved using android JPost library.

JPost让您定义可以发送事件的 channel 。 channel 订阅者仅接收消息。您还可以选择需要接收消息的订阅者。

要实现此操作,请按照以下步骤操作:

Step 1: Create a public channel

public static final int publicChannel1 = 1;
.....
try {
    JPost.getBroadcastCenter().createPublicChannel(ChannelIds.publicChannel1);
}catch (AlreadyExistsException e){
    e.printStackTrace();
}

Step 2: Add subscribers to this channel with subscriberIds

    public static final int  SUBSCRIBER_A_ID = 1;
    ....
    try {
        JPost.getBroadcastCenter().addSubscriber(ChannelIds.publicChannel1, subscriberA, SUBSCRIBER_A_ID);
    }catch (Exception e){
        e.printStackTrace();
    }

类似地,使用不同的订阅者 ID 将所有 4 个类添加到此 channel 。

Step 3: Broadcast the Message event to the selected 2 classes.

    try {
        JPost.getBroadcastCenter().broadcastAsync(ChannelIds.publicChannel1, message, SubsciberA.SUBSCRIBER_A_ID, SubsciberB.SUBSCRIBER_B_ID);
    }catch (JPostNotRunningException e){
        e.printStackTrace();
    }

Step 5: Receive events in the subscriber class.

@OnMessage(channelId = ChannelIds.publicChannel1)
private void onMessage(Message msg){
    System.out.println(msg.getMsg());
}

Note: If in Android you need to update the UI then add @OnUiThread to this method

更多详情请参见 -> https://github.com/janishar/JPost

关于java - 如何在android中发送事件让我们可以选择订阅者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892954/

相关文章:

java - 如何在 Java 中制作倒置列表?

java - 通过 JNI 的数据未正确传递

docker - 如果 Google PUBSUB 中没有来自发布者的消息,如何让订阅者休眠

android - 如何使用 getFragmentManager 将包传递给另一个 fragment

javascript - PubNub - 曾经有效但不再有效的代码

arduino - MQTT client.publish() 和 delay()

java - 在构造函数中创建数据时如何对 java 方法进行单元测试

Java 字符串 : private static vs local variable performance

java - 最好的选择?编译前编辑字节码(asm)或编辑java文件

android - 带有 TextView 和切换按钮 i= 的 ListView 实现