Is there a solution to create a one second delay between the quests we send with Okhttp3?
This means, for example, if the user sent 10 requests, check if the previous request interval was one second by now, otherwise the app will wait for one second, then do the sending work.
I checked this link but it did not work:
How can I queue up and delay retrofit requests to avoid hitting an api rate limit?
The shown examples in linked question didn't work for me too. So I made a research and found this OkHttp Delay Interceptor library. You can just call .addInterceptor(DelayInterceptor(Long, TimeUnit)) method on your's OkHttp client builder object to set a specific delay for requests.
Related
I am creating an app which is like queue displaying. For my scenario, the queue data is always updating. Is there any method that enable I efficiently calling API to get latest data, beside using Handler. Using Handler, might can solve my issue but it's not a good practise because keep calling API for every 5 seconds, might causing server overload/ memory issue? Btw, the API is restful API.
You can implement RxJava with Retrofit such that the Retrofit Service is called every x seconds in your Android Application.
RxJava - is a Java VM implementation of ReactiveX a library for
composing asynchronous and event-based programs by using observable
sequences
In order to create a Retrofit service that runs after certain time intervals, we can use the following :
Handlers (are used to pass data from the background thread to the UI thread)
RxJava
Using RxJava we can do much more than that and very easily as well, using RxJava operators.
We can use the interval operator to call a certain method ( retrofit network call in this case) after every given period.
Observable.interval operator is used to emit values after certain intervals. It looks like this:
Observable.interval(1000, 5000,
TimeUnit.MILLISECONDS);
1000 is the initial delay before the emission starts and repeats every 5 seconds.
We can subscribe our observers which would call the Retrofit method after every 5 seconds.
Calling Retrofit service after certain intervals is fairly common in applications that provide live updates, such as Cricket Score application, etc.
For more details,
Basics of RxJava and Retrofit together
Android Retrofit call every x seconds
I understand you need to update the data when there is the latest data on the server.
I think you need to apply Socket.io for server and client. When the server has new data, it will notify the client through the socket.
Method 1: When the server sends the event to the client, it will send the latest data.
Method 2: When the client receives the event, it will call the API to get the latest data.
This is advisable because when the number of users is very large, it will save resources.
I used to have a problem like yours and found it a bad thing to have clients calling APIs all the time.
Another way is that when the user clicks or manipulates you will call the API to update the data, but this is not recommended
I have a case where some users end up in a loop of requesting #GET API call too often.
Too often = 10-20x every second.
Currently, I've not located the problem and it seems that it's not going to be an easy fix, but I was wondering, is there a possibility to set some kind of limitations on Retrofit2, where if the app goes into some kind of loop where single API request is called so many times, it actually ignores these requests, for instance, do 1-5x same requests in a second max. or something similar?
How could this be done (from a networking library settings perspective)? (Till I find the root cause, I'd like to protect backend)
According the this answer you can use dispatcher as below:
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(1);
OkHttpClient client = new OkHttpClient.Builder()
.dispatcher(dispatcher)
.build()
After then you will be able to send one request on a time.
I have to send four different request in an api at the same time. Do i need to make AsyncTask background thread for each request or all request could be done through a single AsyncTask. Can somebody please help.
This is a concurrency issue. There is literally dozens of ways to do this in Android. I've written almost every single one for courses that cover this material... and even then it isn't 'simple'.
I'd personally make use of HaMeR (Handler, Messages, Runnable) framework of Android. Create 4 runnables and have them post their results to a Handler.
However... That isn't the easiest to implement. and would require you to understand how to safely create your own custom handler (making use of WeakReference properly, etc.)
Therefore, I'd recommend running the asyncTask(s) on the executorService
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); The default thread pool executor should start with 4 threads (I believe off-hand without looking it up).
I am assuming you are using HttpURLConnections. Unfortunately each of those connections, as specified in the documentation, is capable of handling only a single request.
However, you can (and possibly should) still perform all your requests in a single AsyncTask. Each AsyncTask will require the creation of a new thread which takes lots of time and resources. So don't listen to anyone who tells you to create a new task for each request.
You also have the option of exploiting HTTP persistence. If you add the header Connection: Keep-Alive to your request via connection.setRequestProperty("Connection", "Keep-Alive");, you will be able to send multiple requests over the same connection and save a lot of time and resources.
It's a little complicated in Java, because of the one-request-per-httpurlconnection rule, but it can be done. First, when you are done with your first request's HttpURLConnection do not close that connection. Then, to create the next connection, call url.openConnection() on the same URL object that you used to create your first HttpURLConnection. The JVM will know to reuse that connection if possible to save bandwidth.
You also have the option of using HTTP/2.0 multiplexing, which allows you to send multiple requests literally at the same time. Unfortunately I am not yet well versed enough in HTTP/2.0 to tell you exactly how to make use of this, but the multiplexing feature was included to solve exactly this problem.
I have 2 class of AsyncTask for handling request one for sync and other class for handling other request but when I send sync request and move to other page and request response for second request will get after sync request responds. How I solution this?
Hope any one help me
Basically you can use Volley
Volley offers the following benefits:
Automatic scheduling of network requests.
Multiple concurrent network connections.
Transparent disk and memory response caching with standard HTTP
cache coherence.
Support for request prioritization.
Cancellation request API. You can cancel a single request, or you
can set blocks or scopes of requests to cancel.
Ease of customization, for example, for retry and backoff.
Strong ordering that makes it easy to correctly populate your UI
with data fetched asynchronously from the network.
Debugging and tracing tools.
You can easily find a tutorial for it and
It much faster then AsyncTask .
For reference check this
You can make asyntask run parallel execution by replacing execute() with executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR).
I am using volley library for performing network operation to speed up the things. My Question is that Does Volley executes the requests which have added in the queue sequentially or parallel.
Suppose I add request like Req1, Req2, Req3 , Will they start to run parallel or second request will wait until first finished ??
According to the Volley documentation
Volley maintains several network threads. If a thread is not doing anything, then it will take on a job in the queue.
To answer your question, Req1, Req2 and Req3 will each be placed in a worker thread and will run in parallel.
Volley also caches your downloaded data (and determines whether to re-download based on the expire time in the HTTP header of the downloaded data), so if your data doesn't need to be downloaded again, it's fetched from the cache, which is faster than re-downloading.
These are some of the reasons that Volley is proclaimed to be faster than standard network operations for the situations that it's appropriate to use it. You can, of course, implement this yourself, but Google has done a lot of the hard work for you.
Usually a queue starts each operation according to the order it was queued, unless it's a priority queue.
Therefore, assuming equal priority (Assuming that the Volley queue is non priority queue), we can conclude that Req1 will get started first. Then Req2, followed by Req3.
However, we can not guarantee the order which each finishes. If Req1 is time consuming, then the requests will finish in a different order than Req1, Req2, Req3.
All we can guarantee is that they will be started in the order Req1, Req2, Req3.