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.

Observations

  • Scope and job are almost the same
  • Providing a different context or using withContext in both the scenarios the scope and job are newly spawned.
  • Important to notice is launching a coroutine using launch returns a job but withContext does not return a job --> Meaning withContext is still under the umbrella of its immediate parent co-routine.
  • Point to note that withContext returns a result instead of a job but internally it uses a job.
  • The withContext function itself doesn't launch a new coroutine. Instead, it is a suspending function that switches the coroutine context for the specified block.

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
<--------------------------------------------->
Returned value 100

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()
             val result = withContext(Dispatchers.Main + CoroutineName("Child-nested-Coroutine")){
                printCoroutineScopeInfo()
                100
            }
            println("Returned value $result")
        }
    }

}
Clone this wiki locally