0

Suppose our app has 3 activities: A, B and C. And only A is registered to EventBus at onStart() and unregistered at onStop() as explained here, and it has an event handler method: onEvent(X event){...} which navigates the user to C upon receiving of the event X.

But see below unhappy scenario:

  1. User launches A.
  2. User starts a background operation on A.
  3. User navigates to B by tapping a button on A without waiting for the background operation to be completed. A will be unregistered from EventBus.
  4. User navigates back to A. A will be registered to EventBus again.
  5. The background operation which was requested before the user navigated to B is completed, an event X is fired from the background.
  6. Event X is delivered to A, and the event handler (onEvent(X event){...}) navigates the user to activity C immediately.

This is a weird user experience, how can we avoid the event to be delivered to A when it is registered again?

One solution is to cancel the ongoing background operations at onStop(), so that the event will never be fired; however, cancelling a background operation may not always be possible.

I am using the EventBus of GreenRobot.

atakan
  • 133
  • 1
  • 1
  • 8

2 Answers2

0

you can use a counter for your Bus

for example have a static int field in your activity and increase it every time you register a Bus for that activity and when initializing your background task, pass that counter to your task and send it back when it completed. then in your event handler, check that value with current value of your counter and if they were not same , do nothing.

Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36
0

I am not sure what is the expected behaviour here, what should the app do when the user is at A and the background task is finished? ignore the event?

In any case, I would use the event payload (you can define an Event class with its own payload) to control the workflow and for example, in the handler check if that event should be ignored or not.

Joan S.
  • 150
  • 7
  • Well in this case, either unregister EventBus from activity A (if you don't need any other event there) or use a specific event class that the event handler in activity A is not expecting (onEvent()). – Joan S. Jan 27 '16 at 11:42