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

Coroutine入門

curry-like
September 10, 2021

 Coroutine入門

curry-like

September 10, 2021
Tweet

More Decks by curry-like

Other Decks in Programming

Transcript

  1. Coroutine入門
    ゴール: Coroutineとはなんなのかざっくりとわかる

    View Slide

  2. Coroutineとは?
    とても軽量なスレッドのようなもの
    処理の中断・再開ができる

    View Slide

  3. Gradleの設定
    plugins {

    id 'org.jetbrains.kotlin.jvm' version '1.5.20'

    }

    group = 'me.user'

    version = '1.0-SNAPSHOT'

    repositories {

    mavenCentral()

    }

    dependencies {

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'

    testImplementation 'org.jetbrains.kotlin:kotlin-test'

    }

    test {

    useJUnitPlatform()

    }

    compileKotlin {

    kotlinOptions.jvmTarget = '11'

    }

    compileTestKotlin {

    kotlinOptions.jvmTarget = '11'

    }

    View Slide

  4. CoroutineScope
    CoroutineContext
    Dispatcher
    Job
    CoroutineContext: Coroutineの環境を表す値のMap。どのスレッドでCoroutineを実行する
    かなど

    View Slide

  5. CoroutineScope
    Coroutine
    Coroutine
    Coroutine
    Coroutine
    Coroutine
    Coroutine
    CoroutineScope: Coroutineが所属する領域
    CoroutineBuilder: launchやasyncのような

    View Slide

  6. example
    fun main(args: Array) = runBlocking {

    (1..5).forEach { i ->
    launch {

    callApi(i)

    }

    }

    println("end")

    }

    suspend fun callApi(id: Int) {

    delay(1000L)

    println(id)

    }

    runBlocking: 現在のスレッドをラムダ内の処理が終わるまで止める
    launch: Coroutineの作成
    delay: ライブラリが提供しているSuspend Function。Thread.sleepのようなもの
    suspend: Coroutineを中断する関数の修飾詞

    View Slide

  7. 実際にAPIを叩いてみる場合。
    fun main(args: Array) = runBlocking {

    (1..5).forEach { i ->
    val result = async { callApi() }

    val result2 = async { callApi() }

    println(result.await())

    }

    println("end")

    }

    suspend fun callApi(): String {

    val url = URI("https://example.com")

    val client = HttpClient.newBuilder().build()

    val handler = HttpResponse.BodyHandlers.ofString()

    val request = HttpRequest.newBuilder().uri(url).build()

    return withContext(Dispatchers.IO) {

    client.send(request, handler)

    .body()

    }

    }

    withContext: バックグラウンドで非同期処理をする。

    View Slide

  8. 種類
    launch
    async
    などなど
    asyncは呼び出し側で使うことを推奨されているみたい。

    View Slide