KotlinConf 2018 報告会 Coroutines おさらい

KotlinConf 2018 報告会 Coroutines おさらい

99dec28d69a44e5b554e9c3f360e280e?s=128

Akira Iwaya

October 19, 2018
Tweet

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 • Coroutine launch { delay(1000) }

  3. 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
  4. 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
  5. 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
  6. 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 { ... }
  7. None