I’m comparing KC to Goroutines, Java Futures, C# Tasks, RxJava and RxKotlin (Observable Patterns), though most of my work involves writing C for Cortex-M microcontrollers.
For instance, KC’s let me easily compose functions with timeouts which are common for communication protocols.
suspend fun sendRadioCmd(): Boolean {
val radio = Radio()
val timeout = 1000L
return withTimeoutOrNull(timeout) {radio.sendCmd()} ?: false
}
This KC example is somewhat contrived, but in effect, it’s a simple operation where we’re referencing a radio device and then sending a command. If it doesn’t return within 1 second then we’re passed a null and we return false by default.
Kotlin drops this suspendable function into a anonymous class of a Finite State Machine, where each call to a suspendable function acts as a label for the FSM where it can be paused safely.
I will admit, this system is helped along by JetBrains’s IDEs as it will mark which of the functions you are calling are marked with the suspend keyword (in this case sendCmd() and withTimeoutOrNull()), but forcing coroutines to only be able to be called by other coroutines does help restrict some of the viral nature of the syntax, among other advantages.
I will also say that I am excited for the direction of Futures 0.2 and in particular the design space for async programming on embedded devices with the potential ability to pin generators to the stack (so I can stop hand coding so many state machines!). I see the Embedded WG has touched upon this on Wednesday already.