I have a "service" which has a CoroutineScope insi...
# coroutines
d
I have a "service" which has a CoroutineScope inside and I want clients to be able to "dispose" this service, but I want Scope to be an implementation detail. But I'm not against returning some kind of other disposable object. I'd settle with
Copy code
interface Service {
  fun start(): Job
}

val job = myServiceInstance.start()
job.cancel()
is it ok to implement start like
Copy code
fun start() { val scope = createScope(); return scope.coroutineContext[Job] }
Or is there some better way?
s
What about this:
Copy code
interface Service {
  fun start()
  fun cancel()
}

myServiceInstance.start() 
myServiceInstance.cancel()
Where
myServiceInstance
contains a (private) CoroutineScope that is used by
start
and cancelled by
cancel
.
d
I used to do this, but now I don't like this design, because it leaves more room for error: for example I can do cancel() without even starting.
e
I frankly think it is Ok to return a
Job
as a thing you can use to cancel the service. It is explicitly designed for such use. (Btw, in the prototype design it was called a
Lifetime
)
The great thing is that you can create this
Job
(and a scope) even before that
start
is called to keep them in private `val`s inside your class.
So,
start
will then
launch
some coroutines in your scope and will simply return the job of the scope.
Alternatively, if all you have is one coroutine running inside, you can simply return a
Job
that
launch
returns.
d
The great thing is that you can create this
Job
(and a scope) even before that
start
is called to keep them in private `val`s inside your class.
Oh, nice, this is something I should try! Currently I mess with nullable
_scope
etc which is not as great as not doing this dance 🙂 I do launch several coroutines, so it's the first option for me.
s
I guess "it depends" 😁 If the service-impl wants to manage all the lifecycles, my response on your question would be better, I think. If the caller wants to manage the lifecycles, returning a Job and managing those will better (your original version).
1