greenrobot / EventBus

Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
http://greenrobot.org/eventbus/
Apache License 2.0
24.67k stars 4.66k forks source link

Id Added To subscribers #682

Open muhammadzadeh opened 2 years ago

muhammadzadeh commented 2 years ago

Please consider the following scenario: In Messenger, there is a list of chats that need to be updated. Therefore, this must happen by sending an event. The specified event is sent to all rows of chats by default. But we need to send the chat update event in only one row. In this case, the ID is used. Eventbus-by-id

andob commented 2 years ago

Instead of using IDs inside the library, why don't you create more descriptive event classes?

For instance, on your given example, say, you have a class describing a row with an user and its last message:

public class UserRowView
{
   ...
   @Subscribe
   public void onMessageReceived(String message)
   {
        lastMessageTextView.setText(message);
   }
   ...
}

You can reorganise the code like this:

class OnMessageReceivedEvent { text : String, receivedFromId : int }

public class UserRowView
{
   private int userId;
   //todo show user name, its last message, set userId
   ...
   @Subscribe
   public void onMessageReceived(OnMessageReceivedEvent event)
   {
        if (event.receivedFromId == userId)
        {
            lastMessageTextView.setText(message);
        }
   }
   ...
}
muhammadzadeh commented 2 years ago

You are right. We just have to keep in mind that sending events to a large number of subscribers does not make sense when we are on the list.