Search code examples
androidkotlinrx-javarx-androidreactivex

ReactiveX and Android Background Services


This is more of a conceptual question than a matter of programming.

I am currently using ReactiveX (RxJava + RxAndroid) to run an interval timer, as the other methods of timers are too inaccurate when it comes down to the milliseconds. From what I understand, ReactiveX requires several threads to operate correctly.

I need the timer to also be running in the background when the user is not on the app itself. But from reading the Services documentation, it seems that background services can only run on the main thread. I was wondering if it is still possible to run the ReactiveX timer in the background despite this limitation. Implementing services would require some major changes to my project, so I thought that I would try asking before doing so.

The project is written in Kotlin, but I doubt that matters. However, any insight on what this code would look like in Kotlin would be appreciated!


Solution

  • Even though the actual work is done in the background, it seems appropriate to use a foreground service, not a background service. A background service can easily be stopped by the system or even be deferred to maintenance (time) windows. In order to get a "foreground" for the service it is common to use a notification and bind to it: https://developer.android.com/guide/components/services#Foreground

    As to the other question: The life cycle functions of a Service like onStartCommand() might be called on the main thread but you'd be using RxJava to switch to another thread instantly and return from those functions. Even after the lifecycle return, the service is considered "running" to the system. They just exist so get things going and should return promptly.

    Workmanager is not necessarily a good choice here as it is designed for deferrable tasks. So you cannot be sure when it exactly will be started. Foreground service seems like the way to go here.