-
Notifications
You must be signed in to change notification settings - Fork 22
Difference between launch and withContext
Devrath edited this page Jan 15, 2024
·
8 revisions
- Sometimes, We launch a new
co-routine
and sometimes we usewithContext
, There is a bit of difference between the two.
-
Scope
andjob
are almost the same - Providing a
different context
or usingwithContext
in both the scenarios thescope
andjob
are newly spawned. - Important to notice is launching a coroutine using
launch
returns ajob
butwithContext
does not return a job --> MeaningwithContext
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 asuspending function
thatswitches
thecoroutine 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")
}
}
}