It is necessary every 30 seconds to download data from the server and process them in a certain way. (Used by retrofit2 for requests to the server). There are no problems with sending single requests to the server, but I don’t know how to send a request every 30 seconds, I ask for your help.

ps Yesterday I asked the same question, the respondent offered to implement it through the Service , BroadcastReceiver ended up with such an innocent action as downloading data from the server every x seconds resulted in a few hundred lines of code, although I’m sure that rxJava can still do this as a corny 1 - 2 operators.

  • You can try to use Observable.interval which will perform the necessary timing action, it will work while someone is subscribed to it. I used it in Fragment , and it worked, even when moving to another fragment, so I had to unsubscribe to onDestroyView . True, I'm not sure that such use of interval is safe at all, and will most likely cause a memory leak. - Danil
  • Do you want to hang a background task that performs an action every 30 seconds, and at the same time start it without a service from activation via Rx? Bad idea. Do not even notice how the android will kill this task. After all, services have been created for something, otherwise they would simply create all of the activations or applications with ordinary tasks with tasks and would not steam. Run, according to the comment above, Observable , but in the service. And it is better for such tasks (more economical in terms of resources and more reliable) to use FirebaseJobDispatcher. - Vladimir Parfenov

1 answer 1

You will not be able to implement a similar task without service. Moreover, if you need to send a request and receive a response from the server every 30 seconds, you will also have to hang the Notification in the curtain. I will explain:

  • Android is really quite careless about everything that is happening in your application. That is, if you do not use the Service, it just kills what you create because of a banal lack of memory for something else or because he so wanted
  • A regular Service is tied to an Activity, that is, as soon as an Activity dies, the service dies. There are a couple of nuances here - using the IntentService and adding a notification to the curtain. The first untie the service from the activation, the second gives at least a ghostly guarantee that the service will not die after the activation is closed. In addition, you can use the AlarmService to create tasks that repeat over time, but, as you understand, this has nothing to do with Rx.
  • If the normal service is started via startService then it will continue to work after the activation is completed. IntentService will end after the onHandleIntent method is onHandleIntent - temq