我有 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/