Upgrade to Pro — share decks privately, control downloads, hide ads and more …

KotlinConf 2018 報告会 Coroutines おさらい

KotlinConf 2018 報告会 Coroutines おさらい

Avatar for Akira Iwaya

Akira Iwaya

October 19, 2018
Tweet

More Decks by Akira Iwaya

Other Decks in Programming

Transcript

  1. Coroutine ͓͞Β͍1 • No longer experimental since Kotlin v1.3 •

    launch • async • await • suspend 1 https://kotlinlang.org/docs/tutorials/coroutines/coroutines-basic-jvm.html
  2. launch { delay(1000) } • launch runs coroutine on shared

    thread pool • delay suspends coroutine (suspend function) • when coroutine is waiting, the thread is returned to thread pool and resumes later with free thread in the pool • runBlocking runs new coroutine and blocks current thread
  3. async, await val deferred = (1..1_000_000).map { n -> async

    { n } } val sum = deferred.sumBy { it.await() } • async is like launch but returns Deferred<T>. • Deferred<T> has await() • await() returns T, result of the coroutine
  4. async, await • await() must be in coroutine. It suspends

    the computation finishes. • Coroutines can suspend only in coroutine or suspend function Error: Suspend functions are only allowed to be called from a coroutine or another suspend function
  5. suspend fun workload(n: Int):Int { delay(100) // <- suspend function

    returns n } Error: Suspend functions are only allowed to be called from a coroutine or another suspend function • Add suspend modifier to function to fix this and call from a coroutine or another suspend function suspend fun workload(n: Int): Int { ... }