j2emanue
j2emanue

Reputation: 62559

kotlin coroutine - what is default scope?

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 ?

Upvotes: 4

Views: 2933

Answers (2)

Ben Butterworth
Ben Butterworth

Reputation: 28998

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

Upvotes: 1

Kiskae
Kiskae

Reputation: 25603

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.

Upvotes: 2

Related Questions