I have now attempted to address the concern of @kyle-ivey in that responses arriving in between onPause()
and onResume()
are discarded. This is a real issue as I have experienced it in a live application.
My approach builds on the event bus pattern implemented in the answer by Thomas Moerman, although I've reimpemented an example application from scratch. It depends on the Otto Event bus Library, Gson and Volley. It is implemented in IntelliJ 13 Ultimate using Maven tom resolve the dependencies.
Solution: I add to the previous answers a class which acts as a HTTP Response Buffer which takes over the responsibility of listening to events while the Activity is transitioning. When done, the activity actively polls for any responses that may have arrived while the activity was disconnected to the event bus. It hooks on/off in the onPause
and onResume
-events next to the event-bus registering in a fashion like this:
@Override
protected void onPause() {
super.onPause();
ServiceLocator.ResponseBuffer.startSaving(); // The buffer takes over
ServiceLocator.EventBus.unregister(this); // Unregistering with Otto
}
@Override
protected void onResume() {
ServiceLocator.EventBus.register(this); // Re-registering
ServiceLocator.ResponseBuffer.stopAndProcess(); // Process any responses buffered
}
Here is the implementation of the ResponseBuffer-class.
Caveat 1: If the activity is never resumed, and neither stopAndProcess()
nor stopAndPurge()
is called in any future activity, the buffer may be a source of memory leak. Be aware of how you use it. A safe pattern would be to have stopAndProcess()
in onResume()
in all of your activites.
Caveat 2: It is not thread-safe. If there is to come a context switch on the line between where it stars saving and it unregisters the event bus, it may receive the event twice or zero times.
The example includes some test code in the form of UI and support classes, but the main classes you would need if you want to utilize this pattern in a separate projects are the ones in the following packages:
- nilzor.ottovolley.core
- nilzor.ottovolley.messages
See the github-repository OttoVolleyDoneRight for a complete example with UI for testing.
Request
was not already delivered to you? Use a retained fragment for asynchronous operations, so that way regardless of orientation changes, your asynchronous operations have a stable base to communicate to. – JacksVolley
won't deliver responses if we go to background (likeRobospice
), but you are right. We have to callrequestQueue.cancel(...)
to stop the delivery. I'm still thinking of a nice simple way of dealing with re-delivering responses properly duringstop/resume
. – Nevernever