LoginSignup
0
0

More than 3 years have passed since last update.

Kotlinのcoroutineで取得した値を関数の引数として渡す

Posted at

方法は単純で、asyncによって作成したcoroutineを関数の引数に渡す時にawaitを記述すればよい。

これによって関数の実行は戻り値を取得するまで中断され、すべてのcoroutineの引数の戻り値が帰ってきてから関数が実行される。

import java.time.LocalDateTime
import kotlinx.coroutines.*

suspend fun main() = coroutineScope<Unit> {
    println("Before use async: ${LocalDateTime.now()}")
    val bar = async {
        delay(3000L)
        "bar"
    }
    val foo = async {
        delay(2000L)
        "foo"
    }
    val hoge = async {
        delay(1000L)
        "hoge"
    }
    println("After use async: ${LocalDateTime.now()}")
    printHogeFooBar(hoge.await(), foo.await(), bar.await())
    println("After fetch data: ${LocalDateTime.now()}")
}

fun printHogeFooBar(hoge: String, foo: String, bar: String) {
    println("$hoge, $foo, $bar")
}

/*
実行結果
Before use async: 2019-05-31T07:19:42.395
After use async: 2019-05-31T07:19:42.442
hoge, foo, bar
After fetch data: 2019-05-31T07:19:45.450
*/
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0