0

I have 4 classes all subscribed to event Message. I want to send event Message only to 2 of the classes. EventBus is sending event to all the 4 classes.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nikhil
  • 104
  • 8
  • It would be useful to provide some code rather than a scenario. – px06 Oct 06 '16 at 10:00
  • Event emitter should not know about subscribers, you can filter your subscribers by some flag in message or change your subscription logic – Viktor Yakunin Oct 06 '16 at 10:00
  • What if 4 instances of a single class are present. i have to send event to 2 of the instances of that class. – Nikhil Oct 06 '16 at 10:27

1 Answers1

3

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

JPost let you define channels on which events can be send. The channel subscribers only receive the message. You can also choose the subscribers that need to receive the messages.

To implement this follow the following steps:

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();
    }

Similarly add all the 4 classes to this channel with distinct subscriberIds.

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

For More Details See -> https://github.com/janishar/JPost

Janishar Ali
  • 376
  • 3
  • 8