Search code examples
androidgreenrobot-eventbus

Could I use EventBus in Activities communication?


There are three activities A, B, and C

  1. Register EventBus in Activity A onCreate(),and unregister on onDestroy(), and a method onEvent(TestEvent e);

  2. Activity A starts Activity B

  3. Activity B starts Activity C

  4. In Activity C:

    EventBus.getDefault().post(new TestEvent("close A"));
    

I use EventBus in this way , and it works well. Is there anything wrong in my code ?


Solution

  • It's okay. EventBus is thread safe and has a lot of methods to make it easier to work with, like onEventMainThread, onEventBackgroundThread, onEventAsync.

    The thing with your code is this: your activity will continue to get events even if it is in background. And that's okay (in this particular case). If, however, you'll have to implement something else in the future, keep this in mind:

    • onCreate register -> onDestroy unregister
    • onStart register -> onStop unregister
    • onResume register -> onPause unregister

    And there's something else, too: you have to make absolutely sure that your activity is only registered ONCE. Because, if you register more than once, you will receive as many events as the number of registers. Thus, please modify your register like this:

    if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
    }
    

    If you need more details, please read more about EventBus here.

    However, if you follow these simple rules, your activity's lifecycle. I use it a lot and I don't encounter issues.