kotlin coroutine - what is default scope?

2.4k Views Asked by At

How does coroutines default scope work if i do not specify anything. lets take a look at this example:

class MyAppCompatActivity:AppCompatActivity{
fun getContact() {
        GlobalScope.launch {
            val contact = contacts.getContact() // suspended function
            withContext(Dispatchers.Default) {
               phoneContact.value = contact }
        }
    }
}

which simply updates the UI when a contact is retrieved. this is added to the global scope of so the coroutine life span can be that of the entire application.

but lets do the same thing again without a globalScope:

class MyAppCompatActivity:AppCompatActivity{
fun getContact() {
        launch {
            val contact = contacts.getContact() // suspended function
            withContext(Dispatchers.Default) {
               phoneContact.value = contact }
        }
    }
}

what is the lifespan of getContact now that i have removed the globalScope ? is it tied to the MyAppCompatActivity scope ?

2

There are 2 best solutions below

6
Kiskae On BEST ANSWER

Your code will fail to compile because launch must be called on a CoroutineScope object. This object specifies the lifespan of the coroutine. Since your activity does not implement a scope it will fail to compile or call a completely unrelated launch function.

0
Ben Butterworth On

I don't think this is a good idea anymore, as it looks like they're just functions for testing (doesn't launch coroutines). Maybe this was an API available previously, but now you should be using lifecycleScope to scope a coroutine to a fragment or activity, and viewModelScope to scope them to a View Model's life cycle. These are properties available in those classes by already.

Here's what I see when I try to use launch: Possible import suggestions by Android Studio