- 
                Notifications
    You must be signed in to change notification settings 
- Fork 24
Difference between launch and withContext
        Devrath edited this page Jan 15, 2024 
        ·
        8 revisions
      
    - Sometimes, We launch a new co-routineand sometimes we usewithContext, There is a bit of difference between the two.
- 
Scopeandjobare almost the same
- Providing a different contextor usingwithContextin both the scenarios thescopeandjobare newly spawned.
- Important to notice is launching a coroutine using launchreturns ajobbutwithContextdoes not return a job --> MeaningwithContextis still under the umbrella of its immediate parent co-routine.
- Point to note that withContextreturns a result instead of a job but internally it uses a job.
- The withContextfunction itself doesn't launch a new coroutine. Instead, it is asuspending functionthatswitchesthecoroutine contextfor 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 100code
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")
        }
    }
}