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

CLOVIS

08/24/2021, 10:17 AM
When it comes to structured concurrency, it's often said that a class that encapsulates asynchronous operations (for example, a cache, an http client) should take a constructor parameter to explicitly setup structure. Should that parameter be a
Job
or a
CoroutineScope
? So far I've been adding
Job
parameters, but then I have to declare another
CoroutineScope
field per class.
z

Zach Klippenstein (he/him) [MOD]

08/24/2021, 11:48 AM
Not only is there no need to have a
Job
param if you also have a
CoroutineScope
param, but doing so probably makes your API more confusing because it’s not obvious how the explicit job and the job in the scope affect each other.
a

andylamax

08/24/2021, 12:08 PM
In other words, just offer it a
CoroutineScope
☝🏻 1
c

CLOVIS

08/24/2021, 3:02 PM
Thanks! All in all I'm a bit confused as to when one should use
Job
and when one should use
CoroutineScope
. Do you know if there's a good article somewhere on that?
z

Zach Klippenstein (he/him) [MOD]

08/24/2021, 3:20 PM
That’s like asking when one should use a car stereo and when one should use a car. A job/stereo is part of a car, and serves a very specific purpose in the car. A car has way more responsibilities than just playing music, but that is one of the things it can do (by delegating to the stereo).
For API design, in general, it’s more flexible to accept a
CoroutineScope
since it allows the caller to customize not only the
Job
but also any other aspects of the
CoroutineContext
.
d

Didier Villevalois

08/24/2021, 6:52 PM
I generally give a
CoroutineContext
, is that bad ?
z

Zach Klippenstein (he/him) [MOD]

08/24/2021, 6:53 PM
Not imo, there’s some precedent for both
2 Views