如何在 android 中发送我们可以选择订阅者的事件?
How to send events in android where we can choose the subscribers?
我有 4 类 个都订阅了事件消息。我只想将事件消息发送到 类 中的 2 个。 EventBus 正在向所有 4 类 发送事件。
This use case can be very easily solved using android JPost
library.
JPost 允许您定义可以发送事件的通道。频道订阅者只接收消息。您还可以选择需要接收消息的订阅者。
要执行此操作,请执行以下步骤:
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();
}
同样将所有 4 类 添加到具有不同 subscriberId 的频道。
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
我有 4 类 个都订阅了事件消息。我只想将事件消息发送到 类 中的 2 个。 EventBus 正在向所有 4 类 发送事件。
This use case can be very easily solved using android JPost library.
JPost 允许您定义可以发送事件的通道。频道订阅者只接收消息。您还可以选择需要接收消息的订阅者。
要执行此操作,请执行以下步骤:
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();
}
同样将所有 4 类 添加到具有不同 subscriberId 的频道。
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