Search code examples
androidandroid-fragmentsandroid-lifecycleevent-bus

What is the best approach to call register/unregister eventbus on fragments?


I'm brand new using Event Bus from otto lib, So far I created a Event Bus Singleton class, which I'm using in several parts of my code. Now I'm working on a fragment view, But I still have a question, regarding:

When is the best time to register/unregister my event bus?

In a couple of posts I read that onStart() and onStop(), but without any specific reason why.

public class SomeFragment extends Fragment {
  @Override
    public void onStart() {
        super.onStart();
        EventBusSingleton.register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBusSingleton.unregister(this);
    }
}

If I follow the same approach as in the activities doing the call onResume() and onPause() works fine as well.

public class SomeFragment extends Fragment {
  @Override
    public void onResume() {
        super.onResume();
        EventBusSingleton.register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBusSingleton.unregister(this);
    }
}

What could be the potential risk(if exist) from each call way?


Solution

  • onPause()/onResume() is called when your activity does not have the focus anymore but could still be visible (think a dialog or alert on top of your activity).

    onStop()/onStart() is called when your activity is not visible anymore.

    Which one to use depends your use case. I believe it's not really a problem to have callbacks executed while in the paused state so I would just put the register/unregister in onStop()/onStart() but if you really want to make sure, you can put them in onPause()/onResume().