Middle
What is CoroutineScope in Kotlin and how is it used in Android development?
sobes.tech AI
Answer from AI
The CoroutinesScope defines the context and lifecycle of coroutines. It manages a group of child coroutines and cancels them when the scope itself is canceled.
In Android, CoroutineScope is used to bind the lifecycle of coroutines to components like Activity, Fragment, ViewModel.
There are several types of scopes:
GlobalScope: Lives for the entire application. Its use is discouraged due to cancellation complexity and potential memory leaks.ViewModelScope: Provided by KTX library for ViewModel. It is automatically canceled when ViewModel is cleared (onCleared()).LifecycleScope: Provided by KTX library for Activity/Fragment. It is bound to the component's lifecycle and canceled upon destruction. Coroutines can be launched in different lifecycle states (lifecycle.coroutineScope.launchWhenCreated,launchWhenStarted,launchWhenResumed).- Custom scopes: You can create your own
CoroutineScopeas needed.
Example with ViewModelScope:
// ViewModel.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class MyViewModel : ViewModel() {
fun performAsyncTask() {
viewModelScope.launch {
// Async task
}
}
override fun onCleared() {
super.onCleared()
// viewModelScope is automatically canceled here
}
}
Example with LifecycleScope:
// MyActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
lifecycleScope.launch {
// Coroutine will be launched and canceled with Activity
}
}
}
Comparison table:
| Scope | Lifecycle | Recommended for | Notes |
|---|---|---|---|
| GlobalScope | Application lifetime | - | Not recommended, memory leaks |
| ViewModelScope | When ViewModel is cleared | ViewModel | Automatically canceled |
| LifecycleScope | When Activity/Fragment destroyed | Activity/Fragment | Bound to lifecycle |
| Custom Scope | Defined by user | - | Flexible |
Using the correct scope ensures proper cancellation and resource management, preventing leaks and unnecessary work.