Lets say I have a method printCount() that print values every second, I want the polling to stop when the android app is minimized. For an example if it was minimized at count = 15 and if I open it after 5 mins, It should resume the polling and print the count from 16. Polling shouldn't run on background when app is minimized.
- What is the easiest and best way to achieve this in android?
- Also is there a RxJava approach to achieve this?
This can be achieved in many ways, using Handler, RxJava, Coroutines, etc.
Using RxJava:
Observable.interval() method, which emits after a particular time interval specified.
When the app is minimized, onStop() method is called and the observable stops emitting by calling disposable?.dispose(), and starts again in onStart(). I have used global variable for maintaining the count.
Using Kotlin coroutines: