Sobes.tech
Junior — Middle

Millist CoroutineScope kasutatakse tavaliselt Android rakenduste arendamisel?

sobes.tech AI

Vastus AI-lt

In Android development, lifecycleScope is commonly used as a CoroutineScope associated with the component's (Activity or Fragment) lifecycle. This allows coroutines to be automatically canceled when the component is destroyed, preventing memory leaks.

Example usage in an Activity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            // Execute asynchronous task
        }
    }
}

Similarly, for ViewModel, viewModelScope is often used, which cancels coroutines when the ViewModel is destroyed.