scott
scott

Reputation: 3202

Eventbus event subscribers

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 ?.

Upvotes: 1

Views: 1649

Answers (2)

Pankaj Kant Patel
Pankaj Kant Patel

Reputation: 2060

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"));

Upvotes: 1

Ivan Wooll
Ivan Wooll

Reputation: 4323

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.

Upvotes: 2

Related Questions