-
I did a project using kotlin's coroutines, and enjoyed it. I'm exploring giving scala a try and looking to use the same concurency style. I'm trying to figure out how to replicate the below kotlin code using dotty-cps-async, using a single-threaded executor. I can't seem to find an example in the docs of how to do an actual "suspend" that I can "resume" from outside of an async context. My scala is still ok-ish, so it's likely an example/explanation exists in the docs, but it's too obtuse for my current level of understanding of the language. Thanks in advance lateinit var context: Continuation<Unit>
suspend {
val extra="extra"
println("before suspend $extra")
suspendCoroutine<Unit> { context = it }
println("after suspend $extra")
}.startCoroutine(
object : Continuation<Unit> {
override val context: CoroutineContext = EmptyCoroutineContext
// called when a coroutine ends. do nothing.
override fun resumeWith(result: Result<Unit>) {
result.onFailure { ex : Throwable -> throw ex }
}
}
)
println("kick it")
context.resume(Unit) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
For direct work with continuations in Scala you should look at the gears project (https://github.com/lampepfl/gears ) In dotty-cps-async, you can define continuation monad (or use libraries that support continuations, like IO), and you can represent monadic computations in direct style using a compiler plugin see direct context encoding ), but you can't call resume continuation outside async context. By the way, if I remember correctly, the situation in Kotlin is the same: you can call the Some basic examples with user-defined continuation monad can be found in tests: https://github.com/rssh/dotty-cps-async/blob/master/shared/src/test/scala/cpstest/CpsContT.scala. |
Beta Was this translation helpful? Give feedback.
But you can't receive results. In such a way, Scala offers the same capabilities. (i.e., you can call a method on monad, but you can't read the result outside monad).
The direct use of
Continuation
in your example is problematic. If you useContinuation
, then you need Continuation support from the JVM (which, in fact, is Loom) or some monadic continuation interface (IO, ContT, etc.).If only you need to run FFI in a separate thread, then using Continuation is overkill. For FFI calls you can create Future with custom execution context, which evaluates in the dedicated thread and has interface like: