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

simon.vergauwen

01/10/2019, 11:36 AM
Can someone point me in the direction about some info about
Unconfined
&
EmptyCoroutineContext
?
v

Vsevolod Tolstopyatov [JB]

01/10/2019, 3:35 PM
What are you interested in?
Unconfined
is explained in KDoc and
EmptyCoroutineContext
is self-describing
s

simon.vergauwen

01/10/2019, 5:00 PM
I have a stack of bunch of cancel tasks, ~
typealias CancelToken = suspend () -> Unit
. i.e. to unregister callbacks.
On cancellation I want to basically fire and forgot them. They should all run in parallel, since in sequence a never terminating
CancelToken
might blocks others which would cause leaks.
Copy code
typealias CancelToken = suspend () -> Unit

fun main(args: Array<String>) {
  val stack = listOf<CancelToken>(
    { delay(10000000000) }, //blocks forever
    {
      delay(100)
      println("I cancelled first token: ${Thread.currentThread().name}")
    },
    {
      delay(200)
      println("I cancelled second token: ${Thread.currentThread().name}")
    }
  )

  stack.forEach { token ->
    token.startCoroutine(RunAndForgetContinuation())
  }

}

class RunAndForgetContinuation<A> : Continuation<A> {
  override val context: CoroutineContext
    get() = EmptyCoroutineContext

  override fun resumeWith(result: Result<A>) = Unit
}
If I understand the self-describing name
EmptyCoroutineContext
correctly then I can use it to launch a coroutine from any context I am currently in.
a

Allan Wang

01/10/2019, 9:39 PM
I believe that is correct. Child jobs inherit the context from their parent, and adding
EmptyCoroutineContext
to an existing context will result in the same context.
s

simon.vergauwen

01/10/2019, 9:46 PM
so when using
fun (suspend () -> Unit).startCoroutine
with
EmptyCoroutineContext
it forks with the context that is inherited?
Can you point me to any documentation?
a

Allan Wang

01/10/2019, 9:48 PM
I can only point to https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-empty-coroutine-context/index.html But if you look at the source code of the
plus
operator you’ll see the behaviour
I’m not sure how your
startCoroutine
will work. To run your block you’d need a scope to begin with, which is attached to a context
s

simon.vergauwen

01/10/2019, 9:53 PM
startCoroutine
allows me to run a
suspend
function with a continuation that I run on a context. In this case
EmptyCoroutineContext
. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/start-coroutine.html
a

Allan Wang

01/10/2019, 9:57 PM
Probably beyond my scope to help here. Some more info on context can be found in the KEEP: https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md#coroutine-context
s

simon.vergauwen

01/10/2019, 10:00 PM
Thanks, I’ll check it out.
2 Views