https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

vineethraj49

02/13/2020, 7:59 PM
what is the difference between the
block: suspend () -> T
and
block: suspend CoroutineScope.() -> T
types?
o

octylFractal

02/13/2020, 8:02 PM
the second one is usually improper, as it passes two contexts down to the function -- the
suspend
one and the
CoroutineScope
one -- and it's not clear which one will be used
usually you'd stick with either
suspend () -> T
, indicating that it's a normal suspend function that will actually suspend while doing work, or with
CoroutineScope.() -> T
, which indicates that it will launch a separate coroutine that won't suspend this codepath. usually
T
will contain some reference to the Job that was started in this case.
e

Evan R.

02/13/2020, 8:04 PM
The second one could potentially let the suspending function launch coroutines into your current scope. The first one will force
block()
to use
coroutineScope {}
to launch its coroutines and therefore all launched coroutines in
block()
are guaranteed to complete with that signature
l

louiscad

02/15/2020, 8:04 AM
@octylFractal The second one is absolutely NOT improper. That's the signature of
launch
,
async
and
coroutineScope
lambdas. If a custom function creates an inner scope as well, it's totally okay, it's totally to have the lambda(s) have that signature.
5 Views