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

rocketraman

09/13/2018, 5:31 PM
I had a class that created a
newSingleThreadContext
and was passing that to
launch
. Is the right way to do this to now create a
CoroutineScope
that encapsulates that dispatcher, and then call
launch
with that scope?
Also: in the example given in
CoroutineScope
there is an explicit
job
created. Is this necessary or something specific to the Android example? I don't appear to need it in my case but want to make sure I'm not missing something.
Also: in my
shutdown
method of this class, I had
threadContext.close()
-- is
coroutineContext.cancel()
a sufficient replacement for this?
Its not clear to me why the example given in
CoroutineScope
docs does
job.cancel()
rather than
this.cancel()
. Shouldn't cancelling the coroutine scope cancel the job too?
e

elizarov

09/13/2018, 9:49 PM
If you had
launch(ctx)
you can replace it with
GlobalScope.launch(ctx)
— does same thing
You can also implement CoroutineScope in you class and then you can just launch. Makes sense if you do it multiple times.
You still have to close your thread context. Cancel is for Job. Does not close the thread
Scope does not have cancel extension, thus we cannot do
this.cancel()
. Must be
job.cancel()
r

rocketraman

09/13/2018, 9:54 PM
I've implemented
CoroutineScope
and now have:
Copy code
override val coroutineContext: CoroutineContext = newSingleThreadContext("...")
But
CoroutineContext
does not have
close
method to close the thread context of
ThreadPoolDispatcher
.
e

elizarov

09/13/2018, 9:54 PM
Store it in separate val
r

rocketraman

09/13/2018, 9:54 PM
Ok
e

elizarov

09/13/2018, 9:55 PM
Just like job in our example
r

rocketraman

09/13/2018, 9:58 PM
Cool. Some more examples in
CoroutineContext
that are not Android-specific would be nice... I may submit a pull for this 🙂
👍 1
Is there any point to doing
coroutineContext.cancel()
at all?
i

ianbrandt

09/13/2018, 10:02 PM
@rocketraman, I'm finding the non-Android examples in the guide helpful, just in case you hadn't already seen them: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
r

rocketraman

09/13/2018, 10:03 PM
Yeah I need to reread it... haven't read it in a few months... didn't realize there was lots of new stuff!
👍 1
24 Views