Perform asynchronous I/O operations using CoroutineScope/LifecycleScope

Anoop M Madasseri
Tech Log
Published in
1 min readApr 13, 2020

Perform asynchronous I/O operations using CoroutineScope ( https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope ) that define a scope for new coroutines.

In Android, CoroutineScope ships with lifecycle aware architecture components. The KTX extension is ViewModelScope, we can use androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01 or higher.

A ViewModelScope is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. CoroutineScope tied with the ViewModel.

The viewModelScope code is publicly available in AOSP implemented as follows:

https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/lifecycle/lifecycle-viewmodel-ktx/src/main/java/androidx/lifecycle/ViewModel.kt

Usage of ViewModelScopehttps://github.com/anoopmaddasseri/GithubTrendingRepos/blob/3940457412f6dc7f06e86c0a7db2c76ff5c2996f/app/src/main/kotlin/com/mvvmclean/trendingrepos/features/trendingrepo/TrendingRepositoryViewModel.kt#L33

We could also use Coroutines with LifecycleScope as a life cycle aware worker.

A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle is destroyed. You can access the CoroutineScope of the Lifecycle either via lifecycle.coroutineScope or lifecycleOwner.lifecycleScope properties.

Usage of LifecycleScope

activity.lifecycleScope.launch {
// scope tied to Activity Lifecycle
}
fragment.lifecycleScope.launch {
// scope tied to Fragment Lifecycle
}
fragment.viewLifecycleOwner.launch{
// scope tied to Fragment View
}

--

--