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. 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' }
  2. example fun main(args: Array<String>) = 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を中断する関数の修飾詞
  3. 実際にAPIを叩いてみる場合。 fun main(args: Array<String>) = 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: バックグラウンドで非同期処理をする。