Skip to content

Difference between launch and withContext

Devrath edited this page Jan 15, 2024 · 8 revisions

Background

  • Sometimes, We launch a new co-routine and sometimes we use withContext, There is a bit of difference between the two.

output

<--------------------------------------------->
Scope: StandaloneCoroutine{Active}@5c4cf40 
Name: Root-Coroutine
Context: [CoroutineName(Root-Coroutine), StandaloneCoroutine{Active}@5c4cf40, Dispatchers.Main]
Job: StandaloneCoroutine{Active}@5c4cf40
<--------------------------------------------->
<--------------------------------------------->
Scope: StandaloneCoroutine{Active}@771ee79 
Name: Child-Coroutine
Context: [CoroutineName(Child-Coroutine), StandaloneCoroutine{Active}@771ee79, Dispatchers.Main]
Job: StandaloneCoroutine{Active}@771ee79
<--------------------------------------------->
<--------------------------------------------->
Scope: UndispatchedCoroutine{Active}@cc197be
Name: Child-nested-Coroutine
Context: [CoroutineName(Child-nested-Coroutine), kotlinx.coroutines.UndispatchedMarker@9f7cd05, UndispatchedCoroutine{Active}@cc197be, Dispatchers.Main]
Job: UndispatchedCoroutine{Active}@cc197be
<--------------------------------------------->

code

class LaunchAndWithContextDemoVm @Inject constructor( ) : ViewModel() {

    // Create a root co-routine scope
    private val rootScope =  CoroutineScope(
        Dispatchers.Main + CoroutineName("Root-Coroutine")
    )

    private val childScope =  CoroutineScope(
        Dispatchers.Main + CoroutineName("Child-Coroutine")
    )

    fun demo() = rootScope.launch {
        printCoroutineScopeInfo()
        childScope.launch {
            printCoroutineScopeInfo()
            withContext(Dispatchers.Main + CoroutineName("Child-nested-Coroutine")){
                printCoroutineScopeInfo()
            }
        }
    }

}
Clone this wiki locally