1

I was learning Event bus(http://greenrobot.org) in android and i have following code

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);
        EventBus.getDefault().post(new Message("John Testing this event"));
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventOne(Message message) {
        Log.d("ApiCall_1",message.getMessage());
        Toast.makeText(getApplicationContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventTwo(Message message) {
        Log.d("ApiCall_2",message.getMessage());
        Toast.makeText(getApplicationContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onStart() {

        super.onStart();


    }

    @Override
    public void onStop() {

        EventBus.getDefault().unregister(this);
        super.onStop();

The above trigger both subscribers onMessageEventOne and onMessageEventtwo.So my question is 1.Is there any way to trigger particular subscriber ?.

scott
  • 3,112
  • 19
  • 52
  • 90

2 Answers2

2

With an EventBus you are subscribing to broadcasts of a certain type. If you want different functions to be called in the same activity you will need to broadcast different types.

Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34
1

I assume event bus are using java pojo object as an identifier and sending events to all registered receiver objects at a time.

http://greenrobot.org/eventbus/documentation/how-to-get-started/

So define 2 pojo classes and you have to change:

EventBus.getDefault().post(new Message("John Testing this event"));

to

// Event type one
EventBus.getDefault().post(new MessageOne("John Testing this event"));

// Event type two
EventBus.getDefault().post(new MessageTwo("John Testing this event"));
Pankaj Kant Patel
  • 2,050
  • 21
  • 27
  • Kant.thanks.is there way to us same pojo class for both and trigger particular subscriber – scott Jan 21 '18 at 16:39
  • 1
    You could just have the one Subscriber and add a field to your Message class to differentiate between the two types – Ivan Wooll Jan 21 '18 at 16:42
  • 1
    @vision I don't think same pojo can be used for diffrent type of Event's. but what we can do is we can set some flags inside that pojo class like new Message("type1","John Testing this event"),new Message("type2","John Testing this event") – Pankaj Kant Patel Jan 21 '18 at 16:42
  • @PankajKantPatel.ya that might be we can use.thanks for that – scott Jan 21 '18 at 16:43
  • @IvanWooll.thanks for the comment.it helps me to do somethink new. – scott Jan 21 '18 at 16:44