Learning Android Development

Understand Android Lifecycle Aware Coroutine Scope Made Easy

Manage lifecycle more elegantly with Android provided Coroutine Scopes

--

Photo by Minnie Zhou on Unsplash

To use Kotlin Coroutine, we need to have the appropriate scope defined. The tricky bit of it is, we have to remember to create, and stop them. In view of that, the Google Android development team has provided us with some Coroutine Scopes that are aware of its lifecycle.

Below, I’ll try to illustrate them below so that one can easily understand them.

In the examples, when I use lifecycleScope for Activity, it is viewLifecycleOwner.lifecycleScope for Fragment.

To learn specifically on Fragment check out

1. Repeat (restart) the Coroutine Scope Every Time on Specific Lifecycle

Sometimes we need to have some function executed whenever we are in a specific lifecycle and stop immediately when outside the lifecycle stage, e.g. a LiveData observer.

To understand, I wrote a counter code.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
var value = 0
repeat(10) {
delay(1000)
Log.d("Track", "value ${++value}")
}
}
}
}

When I run it across different scenarios, we can see the counter restart. This is because the coroutine always got restarted when the lifecycle hit onStart. The previous coroutine scope got terminated when onStop.

// Starting
D/Track: value 1
D/Track: value 2
// onBackground and onForeground
D/Track: value 1
D/Track: value 2
// onProcess Death and Restart
D/Track: value 1
D/Track: value 2
// onRotate Screen
D/Track…

--

--