Junior — Middle
How to determine the scope of coroutines in programming?
sobes.tech AI
Answer from AI
The scope of a coroutine (Coroutine Scope) defines the lifecycle and context in which the coroutine runs. In Android, different scopes are usually used to manage the lifetime of coroutines and avoid memory leaks.
For example:
- GlobalScope — coroutines live as long as the application is running, not recommended for UI tasks.
- CoroutineScope linked to the component's lifecycle (e.g.,
lifecycleScopein Activity or Fragment) — coroutines are automatically canceled when the component is destroyed.
Example of using lifecycleScope in an Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleScope.launch {
// Coroutine code that will be canceled when the Activity is destroyed
delay(1000)
println("Coroutine finished")
}
}
}
Thus, the scope of a coroutine is determined by the scope in which it is launched, and this scope manages its lifecycle.