When it comes to structured concurrency, it's ofte...
# coroutines
c
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
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
In other words, just offer it a
CoroutineScope
☝🏻 1
c
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
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
I generally give a
CoroutineContext
, is that bad ?
z
Not imo, there’s some precedent for both