Share
Embed
Fresh Async with Kotlin
Introduction to Kotlin Coroutines for a stable released version with Kotlin 1.3. It covers various async programming styles -- callbacks, futures/promises, and Kotlin suspending functions that are easiest to use of all. It shows integration of Kotlin coroutines with a zoo of futures on JVM, compares them with async/await from other languages, introduces structured concurrency and gives a glimpse of CSP. Presented at GOTO Copenhagen 2018.
Roman Elizarov
November 20, 2018
Transcript
144 slides
-
Speaker: Roman Elizarov • Professional developer since 2000 • Previously
developed high-perf trading software @ Devexperts • Teach concurrent & distributed programming @ St. Petersburg ITMO University • Chief judge @ Northern Eurasia Contest / ACM ICPC • Now team lead in Kotlin Libraries @ JetBrains -
History Simula’67 Coroutines CLU’75 Icon’77 Generators C’72 C++’85 Java’95 C#’00
Kotlin’11 C#’12 async/await Kotlin 1.1 (‘17) Coroutines Exp. C++20? Java XX? Threads Asynchronous Programming Microservices Kotlin 1.3 (‘18) Coroutines Release Erlang’86 Go’09 -
Callbacks: before fun requestToken(): Token { // makes request for
a token & waits return token // returns result when received } 1 -
Callbacks: after fun requestTokenAsync(cb: (Token) -> Unit) { // makes
request for a token, invokes callback when done // returns immediately } 1 callback -
Callbacks: before fun requestTokenAsync(cb: (Token) -> Unit) { … }
fun createPost(token: Token, item: Item): Post { // sends item to the server & waits return post // returns resulting post } 2 -
Callbacks: after fun requestTokenAsync(cb: (Token) -> Unit) { … }
fun createPostAsync(token: Token, item: Item, cb: (Post) -> Unit) { // sends item to the server, invokes callback when done // returns immediately } 2 callback -
Callbacks: before fun requestTokenAsync(cb: (Token) -> Unit) { … }
fun createPostAsync(token: Token, item: Item, cb: (Post) -> Unit) { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } -
Callbacks: after fun requestTokenAsync(cb: (Token) -> Unit) { … }
fun createPostAsync(token: Token, item: Item, cb: (Post) -> Unit) { … } fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync { token -> createPostAsync(token, item) { post -> processPost(post) } } } aka “callback hell” This is simplified. Handling exceptions makes it a real mess -
Futures: before fun requestTokenAsync(cb: (Token) -> Unit) { // makes
request for a token, invokes callback when done // returns immediately } 1 -
Futures: after fun requestTokenAsync(): Promise<Token> { // makes request for
a token // returns promise for a future result immediately } 1 future -
Futures: before fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item, cb: (Post) -> Unit) { // sends item to the server, invokes callback when done // returns immediately } 2 -
Futures: after fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> { // sends item to the server // returns promise for a future result immediately } future 2 -
Futures: before fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> … fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync { token -> createPostAsync(token, item) { post -> processPost(post) } } } -
Futures: after fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> … fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync() .thenCompose { token -> createPostAsync(token, item) } .thenAccept { post -> processPost(post) } } -
Futures: after fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> … fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync() .thenCompose { token -> createPostAsync(token, item) } .thenAccept { post -> processPost(post) } } Callbacks are still here -
Futures: after fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> … fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync() .thenCompose { token -> createPostAsync(token, item) } .thenAccept { post -> processPost(post) } } Composable & propagates exceptions No nesting indentation Callbacks are still here -
Futures: after fun requestTokenAsync(): Promise<Token> { … } fun createPostAsync(token:
Token, item: Item): Promise<Post> … fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync() .thenCompose { token -> createPostAsync(token, item) } .thenAccept { post -> processPost(post) } } But all those operators… -
Coroutines: before fun requestTokenAsync(): Promise<Token> { // makes request for
a token // returns promise for a future result immediately } 1 -
Coroutines: after suspend fun requestToken(): Token { // makes request
for a token & suspends return token // returns result when received } 1 natural signature -
Coroutines: before suspend fun requestToken(): Token { … } fun
createPostAsync(token: Token, item: Item): Promise<Post> { // sends item to the server // returns promise for a future result immediately } 2 -
Coroutines: after suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { // sends item to the server & suspends return post // returns result when received } 2 natural signature -
Coroutines: before suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { requestTokenAsync() .thenCompose { token -> createPostAsync(token, item) } .thenAccept { post -> processPost(post) } } -
Coroutines: after suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } suspend fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } -
Coroutines: after suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } suspend fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } Like regular code -
Coroutines: after suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } suspend fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } suspension points -
• Regular loops Bonus features for ((token, item) in list)
{ createPost(token, item) } -
• Regular exception handing Bonus features try { createPost(token, item)
} catch (e: BadTokenException) { … } -
• Regular higher-order functions Bonus features file.readLines().forEach { line ->
createPost(token, line.toItem()) } -
• Custom higher-order functions Bonus features val post = retryIO
{ createPost(token, item) } Everything like in regular code -
Kotlin suspending functions callback Kotlin Java/JVM suspend fun createPost(token: Token,
item: Item): Post { … } Object createPost(Token token, Item item, Continuation<Post> cont) { … } -
Kotlin suspending functions callback Kotlin Java/JVM Continuation is a generic
callback interface suspend fun createPost(token: Token, item: Item): Post { … } Object createPost(Token token, Item item, Continuation<Post> cont) { … } interface Continuation<in T> { val context: CoroutineContext fun resumeWith(result: Result<T>) } -
Kotlin suspending functions callback Kotlin Java/JVM suspend fun createPost(token: Token,
item: Item): Post { … } Object createPost(Token token, Item item, Continuation<Post> cont) { … } interface Continuation<in T> { val context: CoroutineContext fun resumeWith(result: Result<T>) } -
Kotlin suspending functions callback Kotlin Java/JVM suspend fun createPost(token: Token,
item: Item): Post { … } Object createPost(Token token, Item item, Continuation<Post> cont) { … } interface Continuation<in T> { val context: CoroutineContext fun resumeWith(result: Result<T>) } -
interface Service { fun createPost(token: Token, item: Item): Call<Post> }
suspend fun createPost(token: Token, item: Item): Post = serviceInstance.createPost(token, item).await() natural signature -
interface Service { fun createPost(token: Token, item: Item): Call<Post> }
suspend fun createPost(token: Token, item: Item): Post = serviceInstance.createPost(token, item).await() Suspending extension function from integration library -
Callbacks everywhere suspend fun <T> Call<T>.await(): T { enqueue(object :
Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { // todo } override fun onFailure(call: Call<T>, t: Throwable) { // todo } }) } -
suspend fun <T> Call<T>.await(): T = suspendCoroutine { cont ->
enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } -
suspend fun <T> suspendCoroutine(block: (Continuation<T>) -> Unit): T Regular function
Inspired by call/cc from Scheme -
suspend fun <T> Call<T>.await(): T = suspendCoroutine { cont ->
enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } -
Install callback suspend fun <T> Call<T>.await(): T = suspendCoroutine {
cont -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } -
Install callback suspend fun <T> Call<T>.await(): T = suspendCoroutine {
cont -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } -
Analyze response suspend fun <T> Call<T>.await(): T = suspendCoroutine {
cont -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } -
Analyze response suspend fun <T> Call<T>.await(): T = suspendCoroutine {
cont -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) cont.resume(response.body()!!) else cont.resumeWithException(ErrorResponse(response)) } override fun onFailure(call: Call<T>, t: Throwable) { cont.resumeWithException(t) } }) } That’s all -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } suspend fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } Error: Suspend function 'requestToken' should be called only from a coroutine or another suspend function -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } Can suspend execution -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } Can suspend execution A regular function cannot -
Coroutines revisited suspend fun requestToken(): Token { … } suspend
fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } fun postItem(item: Item) { val token = requestToken() val post = createPost(token, item) processPost(post) } Can suspend execution A regular function cannot One cannot simply invoke a suspending function -
Launch fun postItem(item: Item) { GlobalScope.launch { val token =
requestToken() val post = createPost(token, item) processPost(post) } } coroutine builder -
fun postItem(item: Item) { GlobalScope.launch { val token = requestToken()
val post = createPost(token, item) processPost(post) } } Fire and forget! -
fun postItem(item: Item) { GlobalScope.launch { val token = requestToken()
val post = createPost(token, item) processPost(post) } } Fire and forget! We launch for its side effects -
fun postItem(item: Item) { GlobalScope.launch { val token = requestToken()
val post = createPost(token, item) processPost(post) } } Returns immediately, coroutine works in background thread pool -
fun postItem(item: Item) { GlobalScope.launch { val token = requestToken()
val post = createPost(token, item) processPost(post) } } -
fun postItem(item: Item) { GlobalScope.launch(Dispatchers.Main) { val token = requestToken()
val post = createPost(token, item) processPost(post) } } Dispatcher Just specify the dispatcher -
fun postItem(item: Item) { GlobalScope.launch(Dispatchers.Main) { val token = requestToken()
val post = createPost(token, item) processPost(post) } } Dispatcher And it gets executed on the Main thread -
fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, block: suspend () ->
Unit ): Job { … } A regular function -
fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, block: suspend () ->
Unit ): Job { … } suspending lambda -
Kotlin-way suspend fun postItem(item: Item) { val token = requestToken()
val post = createPost(token, item) processPost(post) } Kotlin suspend fun requestToken(): Token { … } suspend fun createPost(token: Token, item: Item): Post { … } fun processPost(post: Post) { … } -
async Task postItem(Item item) { var token = await requestToken();
var post = await createPost(token, item); processPost(post); } Classic-way C# approach to the same problem (also Python, TS, Dart, coming to JS) C# async Task<Token> requestToken() { … } async Task<Post> createPost(Token token, Item item) { … } void processPost(Post post) { … } -
async Task postItem(Item item) { var token = await requestToken();
var post = await createPost(token, item); processPost(post); } Classic-way mark with async C# async Task<Token> requestToken() { … } async Task<Post> createPost(Token token, Item item) { … } void processPost(Post post) { … } -
async Task postItem(Item item) { var token = await requestToken();
var post = await createPost(token, item); processPost(post); } Classic-way use await to suspend C# async Task<Token> requestToken() { … } async Task<Post> createPost(Token token, Item item) { … } void processPost(Post post) { … } -
async Task postItem(Item item) { var token = await requestToken();
var post = await createPost(token, item); processPost(post); } Classic-way C# returns a future async Task<Token> requestToken() { … } async Task<Post> createPost(Token token, Item item) { … } void processPost(Post post) { … } -
Why no await keyword in Kotlin? The problem with async
requestToken() VALID –> produces Task<Token> await requestToken() VALID –> produces Token concurrent behavior sequential behavior C# C# default -
Kotlin suspending functions are designed to imitate sequential behavior by
default Concurrency is hard Concurrency has to be explicit -
Use-case for async var promise1 = loadImageAsync(name1); var promise2 =
loadImageAsync(name2); async Task<Image> loadImageAsync(String name) { … } Start multiple operations concurrently C# -
Use-case for async var promise1 = loadImageAsync(name1); var promise2 =
loadImageAsync(name2); var image1 = await promise1; var image2 = await promise2; async Task<Image> loadImageAsync(String name) { … } and then wait for them C# -
Use-case for async var result = combineImages(image1, image2); C# var
promise1 = loadImageAsync(name1); var promise2 = loadImageAsync(name2); var image1 = await promise1; var image2 = await promise2; async Task<Image> loadImageAsync(String name) { … } -
Kotlin async function fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async {
… } Kotlin A regular function -
Kotlin async function fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async {
… } Kotlin’s future type Kotlin -
Kotlin async function fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async {
… } async coroutine builder Kotlin -
fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async { … } val
deferred1 = loadImageAsync(name1) val deferred2 = loadImageAsync(name2) Start multiple operations concurrently Kotlin -
fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async { … } val
deferred1 = loadImageAsync(name1) val deferred2 = loadImageAsync(name2) val image1 = deferred1.await() val image2 = deferred2.await() and then wait for them await function Suspends until deferred is complete Kotlin -
fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async { … } val
deferred1 = loadImageAsync(name1) val deferred2 = loadImageAsync(name2) val image1 = deferred1.await() val image2 = deferred2.await() val result = combineImages(image1, image2) Kotlin But what if this crashes? Crash? -
fun loadImageAsync(name: String): Deferred<Image> = GlobalScope.async { … } val
deferred1 = loadImageAsync(name1) val deferred2 = loadImageAsync(name2) val image1 = deferred1.await() val image2 = deferred2.await() val result = combineImages(image1, image2) Kotlin Crash? This one leaks But what if this crashes? -
Idiomatic: Using async function when needed suspend fun loadImage(name: String):
Image { … } Is defined as suspending function, not async -
Idiomatic: Using async function when needed suspend fun loadImage(name: String):
Image { … } suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } Structured concurrency -
Idiomatic: Using async function when needed suspend fun loadImage(name: String):
Image { … } suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } -
Idiomatic: Using async function when needed suspend fun loadImage(name: String):
Image { … } suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } -
Idiomatic: Using async function when needed suspend fun loadImage(name: String):
Image { … } suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } -
Kotlin approach to async requestToken() VALID –> produces Token async
{ requestToken() } VALID –> produces Deferred<Token> sequential behavior concurrent behavior Kotlin Kotlin default -
Structured concurrency suspend fun loadImage(name: String): Image { … }
suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } -
Crash suspend fun loadImage(name: String): Image { … } suspend
fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } Crashes? -
Cancels scope suspend fun loadImage(name: String): Image { … }
suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } Cancels -
Cancels children suspend fun loadImage(name: String): Image { … }
suspend fun loadAndCombine(name1: String, name2: String): Image = coroutineScope { val deferred1 = async { loadImage(name1) } val deferred2 = async { loadImage(name2) } combineImages(deferred1.await(), deferred2.await()) } Cancels -
Kotlin suspending functions may use concurrency internally, but don’t leak
it Concurrency needs to be structured -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } println(fibonacci.take(10).toList()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } println(fibonacci.take(10).toList()) >> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } A coroutine builder with restricted suspension -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } A suspending function in the scope of buildSequence -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } println(fibonacci.take(10).toList()) Synchronous -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) // 1 -
Fibonacci sequence val fibonacci = sequence { var cur =
1 var next = 1 while (true) { yield(cur) val tmp = cur + next cur = next next = tmp } } val iter = fibonacci.iterator() println(iter.next()) // 1 println(iter.next()) // 1 etc ad infinum -
Concurrent Fibonacci sequence val fibonacci = GlobalScope.produce { var cur
= 1 var next = 1 while (true) { send(cur) val tmp = cur + next cur = next next = tmp } } Asynchronous (can be in different thread) -
Concurrent Fibonacci sequence val fibonacci = GlobalScope.produce { var cur
= 1 var next = 1 while (true) { send(cur) val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) = runBlocking { println(fibonacci.receive()) } Another coroutine Asynchronous (can be in different thread) -
Concurrent Fibonacci sequence val fibonacci = GlobalScope.produce { var cur
= 1 var next = 1 while (true) { send(cur) val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) = runBlocking { println(fibonacci.receive()) } Another coroutine Receives from channel Asynchronous (can be in different thread) -
Concurrent Fibonacci sequence val fibonacci = GlobalScope.produce { var cur
= 1 var next = 1 while (true) { send(cur) val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) = runBlocking { println(fibonacci.receive()) // 1 } -
Concurrent Fibonacci sequence val fibonacci = GlobalScope.produce { var cur
= 1 var next = 1 while (true) { send(cur) val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) = runBlocking { println(fibonacci.receive()) // 1 println(fibonacci.receive()) // 1 } etc ad infinum -
Kotlin coroutines Standard library kotlinx-coroutines launch, async, runBlocking, Job, Deferred,
etc http://github.com/kotlin/kotlinx.coroutines