Networking in Android is hard. The standard pattern has been to pass a callback to the service performing the request, which performs some action on completion. Often these callbacks are anonymous inner classes created inside your Activity or Fragment. This works fine – until the user rotates their device, or hits the home button, or switches to another app. Then your Activity can be destroyed before the callback returns, resulting in your activity context leaking and your callback updating an Activity that no longer exists.
The issue is not the callback pattern itself – the issue is that the callback is tied to your Activity, but the lifecycle of the request is not. Google has released a networking library called Volley that allows for cancelling requests, tying them to the Activity lifecycle, and we have integrated it with our CloudMine library.
Volley works by creating new Request objects which encapsulate all the information needed to make and respond to an HTTP request – URL, headers, body content, success and error listeners, etc. These requests are then added to a RequestQueue, which performs the request. The Requests can be canceled from the RequestQueue, which is what allows us to tie the lifecycle of the Request to the lifecycle of the Activity. An example of this is given below: