Colton Idle
04/27/2024, 10:00 PMstojan
04/27/2024, 10:07 PMColton Idle
04/27/2024, 10:08 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>) {
launch{...}
streetsofboston
04/27/2024, 11:09 PMcoroutineScope { .... launch { .... } .... }
The coroutineScope
method brings the calling CoroutineScope (the scope in which the suspend function was called) into the lambda provided to it (its this
receiver). Note that, due to structured concurrency, all launched (launch, async) children must finish/complete before the suspended call to coroutineScope
resumes.kevin.cianfarini
04/28/2024, 1:45 AMcoroutineScope
method brings the calling CoroutineScope (the scope in which the suspend function was called) into the lambda provided to it (its this
receiver).
>
This is not true. The coroutineScope
builder function creates a new coroutine scope that is a child of the coroutine executing the current suspending function. From the docs:
> Creates a CoroutineScope and calls the specified suspend block with this scope. The provided scope inherits its coroutineContext from the outer scope, using the Job from that context as the parent for a new Job.stojan
04/28/2024, 8:44 AMstreetsofboston
04/28/2024, 4:38 PMColton Idle
04/28/2024, 6:26 PMJacob
04/28/2024, 7:38 PMwithContext
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T
Why is block
an extension function of CoroutineScope?
I thought suspend CoroutineScope.()
Was discouraged as it's unclear if the block will launch things concurrentlyJacob
04/28/2024, 8:44 PMwithContext
, will my code be suspended until the launched coroutine completes?kevin.cianfarini
04/28/2024, 9:18 PMwithContext
also make a child coroutine scope that will wait for all launches coroutines to complete before it returnsstreetsofboston
04/28/2024, 9:49 PMblock
is an extension suspend-lambda with a CoroutineScope
as receiver much like the suspend-lambda you provide to a launch
or async
call.
The coroutine framework guarantees that the suspend-lambda's CoroutineScope receiver ( this
) is the same scope in which the suspend-lambda is called, and that it's a CoroutineScope that will finish only when all its possible child coroutines have finished and the suspend-lambda resumes only after that point.
If you create your own suspend CoroutineScope.someFunction(...): SomeType
then that is not the case (unless you manually provide the mechanism/code that would do all that). That's why it's discouraged.