Search code examples
javaandroidpublish-subscribegreenrobot-eventbus

How to send events in android where we can choose the subscribers?


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.


Solution

  • 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