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.
CodePudding user response:
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,
CodePudding user response:
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