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.
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.
class MainActivity : AppCompatActivity() {
private lateinit var counterText: TextView
private var counter: Int = 0
private var disposable: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
counterText = findViewById(R.id.count)
}
override fun onStart() {
super.onStart()
disposable = Observable.interval(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { printCount() }
}
private fun printCount() {
counter++
counterText.text = counter.toString()
}
override fun onStop() {
super.onStop()
disposable?.dispose()
}
}
Using Kotlin coroutines:
class MainActivity : AppCompatActivity() {
private lateinit var counterText: TextView
private var counter: Int = 0
private var job: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
counterText = findViewById(R.id.count)
}
override fun onStart() {
super.onStart()
job = CoroutineScope(Job() + Dispatchers.Main).launch {
while (true) {
printCount()
delay(1000)
}
}
}
private fun printCount() {
counter++
counterText.text = counter.toString()
}
override fun onStop() {
super.onStop()
job?.cancel()
}
}