Cícero Moura
Cícero Moura

Reputation: 2333

EventBus behavior with Activity/Fragment lifecycle

I have registered my activity/fragment like this:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

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

I have a process which is running and posting events with its status to my subcriber method.

For instance, if the user rotates the device, onStop will be called and my activity/fragment will be unregistered and it will not listen to my process events until it register again.

If some events are posted in this short time, what will happen?

(considering that my event bus will not throw any exception because of not having any subcriber registered.)

I really want to handle situations like that when for some reason the activity/fragment is not registered and some events are being posted.

I was thinking about implementing a queue of events that are not received by subscribers so that the UI could do somthing about it when it gets registered again.

Upvotes: 0

Views: 781

Answers (2)

dragi
dragi

Reputation: 3525

You have two types of events: - the ones that signal that something happened and are not really relevant later. For example: car speed became 50 km/h - the other ones that are more like states. For example the car engine is turned off.

If event of the first type is posted, it is usually not a big deal to miss, because there will be another one that will replace the old value (i.e. the speed became 30 km/h). For the second type of events, you probably want to know the last value (or state) because it may not change again very soon. (with the example above, you want to know if you missed the event that the engine was turned off or on, in order to do/show something specific)

This second type of events is usually handled as sticky, for which you use postSticky() and registerSticky() methods. So if your events are posted as sticky, after you call registerSticky() you will get notified for all the sticky events with their last value.

If the last value per event is not enough, then probably you will need to cache the missed events manually.

Upvotes: 0

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

You need to register in the onCreate() and unregister in onDestroy(), something like this:

@Override 
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ...
  // Check if Event Bus is not already register here
  if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
     }
  ...
}

@Override 
protected void onDestroy() {
  // Check if Event Bus is register here, then unregister it.
  if (EventBus.getDefault().isRegistered(this)) {
      EventBus.getDefault().unregister(this);
     }
  super.onDestroy();
}

Upvotes: 1

Related Questions