Android Volley + Loader pattern? - android

I kinda liked Volley framework, but I still have some doubts about it.
For example, how does Volley line up with Loader pattern? Since it's requests are handled in an async manner, calling it on background doesn't make much sense. On the other hand, if we ignore the Loader pattern, we will cancel the loading and reload the necessary resources, it's kinda waste.
How does Volley framework work with Loaders in Android?

A Loader can encapsulate practically anything, including Volley requests. When your Loader encapsulates a framework that already handles background work for you and calls you back on the main thread, like Volley, your loader implementation must not inherit from AsyncTaskLoader but simply from the Loader base class. You would then start the Volley request in the onForceLoad() method.
When your loader gets the result back on the main thread through a callback, it just needs to push it to the Activity/Fragment by calling deliverResult().
Your loader would also need to keep a reference to the Volley request in progress to be able to cancel it in onStopLoading(). onStopLoading() is not called in case of configuration change like screen rotation, only when leaving the Activity.
The only disadvantage is that Loaders don't have a built-in mechanism to propagate errors, while Volley does. So in your Volley error callback inside of your Loader, you'll need to either deliver a null result or send a local broadcast to notify the Activity/Fragment of the error.

AFAIK and I have seen in the sources, responses to your requests will be cached, IF the server sends the proper caching headers(ETag), and the second time you will attempt to make a GET request, to the same url, you will be provided with a response from the cache, instead of calling the Network again.(by default Volley caches the requests using as key the URL).
Adding Requests to the RequestQueue should be done from the MainThread, as it makes no sense to call them from a background Thread.

I just publish an article about Volley and it integration into project over Loader pattern. Advanced approach is shown. Loader states are fully defined and displayed in diagram.
Article: https://plus.google.com/117981280628062796190/posts/8b9RmQvxudb

It is possible to make synchronous requests with Volley via the RequestFuture class. I haven't looked into this personally, but it looks like you could leverage that with a Loader to get the best of both worlds (Volley's Cache with the loading stability of the Loader).

Related

Should Volley onResponse() be handled in a background thread?

I'm using Volley for all my network related code. Since Volley does the actual networking part off the main UI thread I havent really thought much about it but I realize now that in a few instances I do some significant processing of the response data in onResponse(). It seems like this code does indeed run on the main thread. What's the best way to do this? Should I define a AsyncTask for that specific portion of the code or should I just put the entire network request in a AsyncTask despite Volley's threading mechanisms.
I would suggest NOT to use AsyncTask as it has its own drawbacks in case activity is destroyed or recreated. And moreover if you are using Volley's queueing mechanism, this will just work as a add-on.
One solution I can think of is to use Loaders. Make the network call and process the response in loadInBackground method. And when onLoadFinished is called, you'll get the processed response.
Another solution (Not recommended and not so efficient) is to use a Service. You can make the network call from the Service and process the data and communicate back to the Activity.

Android's ContentResolver.isSyncActive returns false before the actual sync is over

I am triggering a sync with a REST service using SwipeRefreshLayout's onRefresh method by calling ContentResolver.requestSync, which launches my Syncadapter.
The Syncadapter then uses Volley's Request to communicate with the server.
To detect the end of the sync operation and close the activity indicator I use ContentResolver.isSyncActive inside SyncStatusObserver of the Fragment from which I initiated the sync.
The problem is that the ContentResolver.isSyncActive returns false before the actual sync with the server is over, causing the activity indicator to disappear almost immediately.
Am I correct assuming that the asynchronous nature of Volley's Request causes the SyncAdapter's onPerformSync to return immediately which, in turn, makes the ContentResolver think that the sync is over?
If yes, what is the correct/recommended solution here? I can come up with workarounds, but wanted to make sure I am not missing something obvious.
I have looked through many examples including iosched, swiperefresh, basicsyncadapter etc., but they all seem to "hold" the onPerformSync method until everything is over.
Thank you
You should make the requests act synchronously inside the onPerformSync method. I use Retrofit for calls with backends but I think Volley should also provide the synchronous functionality.

Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

OKHttp supports both synchronous and asynchronous api.
If I want to issue an async request, I can:
Use a AsyncTask, and issue OKhttp synchronous api.
Issue a OKhttp asynchronous api.
What is the difference between these 2 options? And which one is better?
Quite a lot differs!
Using AsyncTask for HTTP requests is pretty much one of the worst things you can do on Android. It's fraught with problems and gotchas that are best unconditionally avoided. For example, you cannot cancel a request during execution. The patterns of using AsyncTask also commonly leak a reference to an Activity, a cardinal sin of Android development.
OkHttp's async is vastly superior for many reasons:
It supports native canceling. If a request is in-flight, the reference to the Callback is freed and will never be called. Additionally, if the request has not started yet it never will be executed. If you are using HTTP/2 or SPDY we can actually cancel mid-request saving bandwidth and power.
It supports tagging multiple requests and canceling them all with a single method call. This means every request you make in, say, an Activity can be tagged with the Activity instance. Then in onPause or onStop you can cancel all requests tagged with the Activity instance.
If you are using HTTP/2 or SPDY requests and responses are multiplexed over a single connection to the remote server and by using the asynchronous Call mechanism this is much more efficient than the blocking version.
So if you can, use Call.enqueue!
Nothing much. OKHttp async is OKHttp API driven. So as long as you bundle the jars together for all platforms you should be good. AsyncTask is Android way of doing things.
However since Honeycomb Async task runs the tasks sequentially and not in parallel. This means that though the execute method of AsyncTask spans a new thread which runs your job away from the UI thread but all the tasks sent to one AsyncTask run in the same spanned thread.
So for 3 tasks submitted u don't get 3 threads they all run sequentially on a single spanned thread. With OKHttp you can achieve true parallelism using callbacks and async GET and POST.
Though you can do true parallelism in AsyncTask methods as well (check the overloaded execute methods in AsyncTask) but default Android behavior is not to do so.

Volley or ASyncTaskLoader

They tell everywhere that we should use ASyncTaskLoaders because they are very good at not blocking the UI thread. And there is Volley to use now.
I guess we cannot use both of them because Volley does backgrounding on its own. What do you think? Which one is better?
These 2 technologies are different and hardly comparable. They have different purposes and can also work together. You could for exemple implement a Loader that uses Volley to load the data and inherits directly from Loader (not AsyncTaskLoader, because Volley handles the threading as well).
Main advantages of using Loaders:
Lifecycle is synchronized with the Activity/Fragment lifecycle automatically
Data and loading state is not lost on configuration change
The loader monitors changes and pushes new results automatically to the client fragment/activity.
Main advantages of using Volley:
High performance network stack
Automatic disk cache that respects the HTTP server policy
Powerful cancelation mechanism.
You can combine both to get both sets of advantages or you can use Volley without loaders with its simple API.
I've been using Volley for a month now and I have to say that I'm very satisfied. It really does help a lot not to have to worry about threading implementation details. So far both general networking and remote image loading have been working great.
It's not that there are no issues, but so far they have been minimal.
You better ask like this volley vs Async vs RxJava
You can use this RXJava for background thread, but for better efficiency in calling restful services Volley is highly recommended, also very less coding required compare to async task loaders !
Here is a writeup on current Android best practices. It discusses the use of Volley and RXJava: https://github.com/futurice/android-best-practices
You can combine both, to get both advantages.
In your activity (main thread) you call your API with Volley.
With a simple interface mechanism, you callback your main thread when the data is available.
Then you forceLoad() your AsyncTaskLoader with the fresh data from Volley.
In your AsyncTaskLoader you hydrate all your activity's container. They will be automatically loaded when data is available.
With this approch you combine Automatic disk cache of Volley, and Automatic synchronization of Loader.

Robospice: return cached data when network is down

I am starting to use robospice for an application which has to function in regions with changing connectivity.
How would I achieve that robospice would automatically return the cached data when the network is down?
Thanks
Ben
I have not worked with Robospice at all. But from what I can tell it looks like the request class allows you to specify AcceptingDirtyCache by calling
request.setAcceptingDirtyCache(boolean isAcceptingDirtyCache)
there was a thread about this on github that talks about this very problem.
Also not sure since I have never used robospice but you should be able to call CacheManager.loadDataFromCache() to load any data that exists in the cache. So you could utilize this function whenever you need to make a request but the network is down.

Categories

Resources