Can someone point me in the direction about some i...
# coroutines
s
Can someone point me in the direction about some info about
Unconfined
&
EmptyCoroutineContext
?
v
What are you interested in?
Unconfined
is explained in KDoc and
EmptyCoroutineContext
is self-describing
s
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
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
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
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
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
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
Thanks, I’ll check it out.