3. Disclaimer
• Most ideas presented herein are very old
• Simula ‘67 was one of the first languages to
introduce coroutines
• detach – was a coroutine suspension statement
• resume – was to resume coroutine execution
• CLU ‘75 was the first language with generators and
Icon ‘77 was prominently using them
• Coroutines fell out of favor due to emergence of
multithreading
• And now they are back to write asynchronous code
22. A digression on async/await
async function preparePost() {
let request = composeTokenRequest();
let result = await makeRequest(request);
return result.parseToken();
}
async function preparePost(): Promise<Token> {
let request = composeTokenRequest();
let result = await makeRequest(request);
return result.parseToken();
}
JS approach to the same
problem (also TS, C#, Dart, etc)
mark with async
use await to suspend
JS
29. Kotlin approach to async
async function doSomething(): Promise<Result> {
/* ... */
}
Sometimes you need the Promise and async
let request1 = doSomething();
let request2 = doSomething();
1
2
To start multiple operations
concurrently
await request1;
await request2;
JS
and then wait for them
async builder
await function
Returns Deferred<Result>
Suspends until deferred is complete
30. Recap
• Coroutine builders
• launch
• runBlocking
• async
• Suspending functions with suspend keyword
• Can nest to any depth
(not stackless)
• suspendCoroutine
Regular
world
Coroutine
Coroutine Callback
Coroutine Coroutine
32. Library vs language
• Kotlin language only has suspend keyword
• Transforms suspend functions to callbacks
• Compiles code to state machines
• stdlib has Continuation and CoroutineContext
• Everything else is in a library
• It includes launch/join, async/await, runBlocking, etc
• We were using kotlinx.coroutines library
• http://github.com/kotlin/kotlinx.coroutines
• You can study source and contribute
It is designed to be composable
Mix & match different libs
33. Experimental status of coroutines
• This design is new and unlike mainstream
• For some very good reasons
• We want community to try it for real
• So we released it as an experimental feature
• We guarantee backwards compatibility
• Old code compiled with coroutines continues to work
• We reserve the right to break forward compatibility
• We may add things so new code may not run w/old RT
• Design will be finalized at a later point
• Old code will continue to work via support library
• Migration aids to the final design will be provided
opt-in flag
35. There is more
• Channels/Actors
• Selection and synchronization
• Job hierarchies and cancellation
• buildSequence/yield
• Restricted (sync) suspension
• Interop with other futures/promise/reactive libs
• The actual implementation details
• Learn more in Guide to kotlinx.coroutines by example
• KotlinConf on 2-3 November, 2017 in SF