How is the lifecycle of coroutines managed?
sobes.tech AI
Answer from AI
Managing the lifecycle of coroutines in Android is typically done using special CoroutineScope instances that are tied to the lifecycle of components (such as Activity or ViewModel). This allows coroutines to be automatically canceled when the component is destroyed, preventing memory leaks and unnecessary work.
For example, in ViewModel, the viewModelScope is used, which cancels all launched coroutines when the ViewModel is destroyed:
class MyViewModel : ViewModel() {
fun loadData() {
viewModelScope.launch {
// asynchronous work
}
}
}
In an Activity or Fragment, lifecycleScope can be used, which cancels coroutines when the corresponding component is destroyed:
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
// coroutine will be canceled when Activity is destroyed
}
}
}
Thus, the lifecycle of coroutines is closely linked to the lifecycle of components through CoroutineScope, ensuring proper management and cancellation of coroutines.