Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Kotlin Coroutine 基本的な使い方
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
sutetotanuki
November 25, 2019
Programming
910
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Kotlin Coroutine 基本的な使い方
sutetotanuki
November 25, 2019
More Decks by sutetotanuki
See All by sutetotanuki
数案件を同時に進行するためのコンテキスト整理術
sutetotanuki
2
420
高速開発のためのコード整理術
sutetotanuki
1
1k
Next.js 16の新機能 Cache Components について
sutetotanuki
0
640
Vercel AI SDK を使って Next.js で AIアプリケーションを 作成する方法のご紹介
sutetotanuki
0
1.9k
WEBエンジニア向けAI活用入門
sutetotanuki
0
1.1k
ブラウザ上で実行され、 AIアシスタント付きデータベース postgres.new を触ってみた
sutetotanuki
0
550
今時のCookie事情
sutetotanuki
0
740
高速案件立ち上げで使われるマッハテンプレートのフロントエンド技術選定
sutetotanuki
2
2.1k
Core Web Vitals を改善する Next.js の機能群
sutetotanuki
1
2.7k
Other Decks in Programming
See All in Programming
ランチタイムLT会3周年!ランチタイムLT会を3年間続けられたお話
y0hgi
1
140
初めてのKubernetes 本番運用でハマった話
oku053
0
130
鹿野さんに聞く!『TypeScriptコードレシピ集』で磨く実践力
tonkotsuboy_com
4
1.1k
Apache Hive: Toward a Cloud Native Lakehouse
okumin
0
130
act2-costs.pdf
sumedhbala
0
110
トークンをケチるな、設計しろ:GitHub Copilotを賢く使うコンテキスト戦略
ochtum
0
320
광주소프트웨어마이스터고등학교 DevFest 특강 - 바이브 코딩 시대에서 주니어 개발자로 살아남는 방법
utilforever
1
140
Prismを使った型安全な暗号化_関数型まつり2026
_fhhmm
0
140
霧の中の代数的エフェクト
funnyycat
1
400
使用 Meilisearch 建立新聞搜尋工具
johnroyer
0
150
Laravel Boostに学ぶ、AIにPHPを書かせる技術 〜OSSの実装から蒸留するエージェント制御の王道〜
kentaroutakeda
3
460
『コードを書く以外の』エンジニアリング〜課金基盤移行プロジェクト推進のためのTips4選
yuriko1211
0
510
Featured
See All Featured
Testing 201, or: Great Expectations
jmmastey
46
8.2k
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
470
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
141
35k
Un-Boring Meetings
codingconduct
0
350
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2.1k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
360
30k
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
0
450
The Art of Programming - Codeland 2020
erikaheidi
57
14k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
201
75k
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
190
Crafting Experiences
bethany
1
220
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
65
56k
Transcript
,PUMJO$PSPVUJOF جຊతͳ͍ํ
w Ϋϥεϝιουגࣜձࣾ w $9ࣄۀ෦ॴଐ w "1*։ൃɺ"84ڥߏஙɺӡ༻ w /&8 "OESPJE
ࠓ͢͜ͱ w $PSPVUJOFͱ w $PSPVUJOFͷ͍Έͪ w جຊతͳ͍ํ w ࣮ྫू
$PSPVUJOFͱ
$PSPVUJOFͱ w ܰྔ5ISFBE w 5ISFBEͷΑ͏ʹѻ͑ͭ͋ͨΓʹඞཁͳϦ ιʔε͕5ISFBEΑΓ͍ܰ w ͨ͘͞ΜىಈͰ͖Δ
$PSPVUJOFͷ͍ಓ 6 ϝΠϯ 6* εϨουͰߦ͏ͱ69ΛଛͶΔ Մೳੑͷ͋Δॏ͍ͨॲཧΛผεϨουͰ࣮ߦ ͢Δ
ॏ͍ͨॲཧ 7 w *0όϯυͷॲཧ w ωοτϫʔΫΞΫηε w σΟεΫΞΫηε w $16όϯυͷॲཧ
w +40/ͷγϦΞϥΠζɺσγϦΞϥΠζ w Ϧετͷฒͼସ͑
جຊతͳ͍ํ
جຊతͳ͍ํ fun main(args: Array<String>) { println("Start") GlobalScope.launch { delay(1000) println("1")
} println("2") println("End") Thread.sleep(2000) } Start 2 End 1
$PSPVUJOFͱ fun main(args: Array<String>) { println("Start") GlobalScope.launch { delay(1000) println("1")
} println("2") println("End") Thread.sleep(2000) } Start 2 End 1 $PSPVUJOFͰ࣮ߦ͞Ε ඇಉظʹॲཧ͞Ε͍ͯΔ
$PSPVUJOFͱ fun main(args: Array<String>) { println("Start") GlobalScope.launch { delay(1000) println("1")
} println("2") println("End") Thread.sleep(2000) } Start 2 End 1 $PSPVUJOF #VJMEFS $PSPVUJOF 4DPQF
$PSPVUJOF4DPQF
4DPQF֊ߏʹͰ͖Δ 4DPQFʹෳͷ$PSPVUJOFΛ࣋ͯΔ
$PSPVUJOF4DPQF fun main(args: Array<String>) = runBlocking { println("Start") GlobalScope.launch {
delay(1000) println("1") } println("2") println("End") } Start 2 End
$PSPVUJOF4DPQF fun main(args: Array<String>) = runBlocking { println("Start") GlobalScope.launch {
delay(1000) println("1") } println("2") println("End") } Start 2 End (MPCBM4DPQF ʹͳΔͨΊSVO#MPDLJOHͷ είʔϓͰऴྃΛ·ͨͳ͍
$PSPVUJOF4DPQF fun main(args: Array<String>) = runBlocking { println("Start") launch {
delay(1000) println("1") } println("2") println("End") } Start 2 End 1
$PSPVUJOFͱ fun main(args: Array<String>) = runBlocking { println("Start") launch {
delay(1000) println("1") } println("2") println("End") } Start 2 End 1 SVO#MPDLJOHͷείʔϓͷUIJT $PSPVUJOF4DPQF SVO#MPDLJOHͷ4DPQFͷMBVODIϝιουͰ ࢠ$PSPVUJOF4DPQFΛ࡞
$PSPVUJOFͱ fun main(args: Array<String>) = runBlocking { println("Start") launch {
delay(1000) println("1") } println("2") println("End") } Start 2 End 1
$PSPVUJOF %JTQBDIFST
$PSPVUJOF%JTQBDIFST 20 $PSPVUJOF͕Ͳͷ5ISFBEͰ࣮ߦ͞ΕΔ͔ ΛׂΓͯΔΈ
༻ҙ͞Ε͍ͯΔ%JTQBDIFST 21 εϨου ࠷దͳॲཧ .BJO ϝΠϯ UIΛมߋ͢ΔؔɻLiveDataͷߋ৽ *0 IOʹ࠷దԽ
ωοτϫʔΫɺσΟεΫΞΫηεͳͲ %FGBVMU όοΫάϥϯυ εϨουͷڞ༗ϓʔϧ CPUͷෛՙ͕େ͖͍ॲཧɻJSONղੳ Ϧετͷฒͼସ͑
$PSPVUJOF%JTQBDIFST fun main(args: Array<String>) = runBlocking { withContext(Dispatchers.IO) { delay(1000)
println("IO: ${Thread.currentThread().id}") } println("Main: ${Thread.currentThread().id}") } IO: 11 Main: 1
$PSPVUJOF%JTQBDIFST fun main(args: Array<String>) = runBlocking { withContext(Dispatchers.IO) { println("IO:
${Thread.currentThread().id}") } println("Main: ${Thread.currentThread().id}") } IO: 11 Main: 1 $PSPVUJOF4DPQFͷUIJTMBVODI ϝιουͰࢠ$PSPVUJOF4DPQFΛ࡞ ͢Δ
4VTQFOE
TVTQFOE 25 தஅɺ࠶։Ͱ͖ΔؔɻTVTQFOEؔ DPSPVUJOFɺ͘͠ผͷTVTQFOEؔ ͔Β͔͠ݺͳ͍
TVTQFOE suspend fun getData(): ApiResponse { return callApi() } fun
main(args: Array<String>) { getData() } Suspend function 'getData' should be called only from a coroutine or another suspend function
TVTQFOE suspend fun getData(): ApiResponse { return callApi() } fun
main(args: Array<String>) { getData() } Suspend function 'getData' should be called only from a coroutine or another suspend function ΤϥʔʹͳΔ
TVTQFOE suspend fun getData(): ApiResponse { return callApi() } fun
main(args: Array<String>) = runBlocking { getData() } DPSPVUJOFΛىಈͦ͠ͷதͰݺͿͱ Τϥʔ͕ൃੜ͠ͳ͍
࣮༻ྫ
7JFX.PEFMͰ͏ fun callApi(name: String): UserResponseBody { val client = OkHttpClient()
val request = Request.Builder() .url("https://api.github.com/users/$name") .build() client.newCall(request).execute().use {response -> return Gson().fromJson(response.body?.string(), UserResponseBody::class.java) } } class MainViewModel : ViewModel() { val response = MutableLiveData<UserResponseBody>() val userName = MutableLiveData<String>() fun getUser() { viewModelScope.launch { response.value = callApi(userName.value ?: "") } } }
7JFX.PEFMͰ͏ class MainViewModel : ViewModel() { val response = MutableLiveData<UserResponseBody>()
val userName = MutableLiveData<String>() fun getUser() { viewModelScope.launch { response.value = callApi(userName.value ?: "") } } } ϝΠϯεϨουͰΠϯλʔωοτΞΫηε ͢ΔͨΊΤϥʔʹͳΔ WJFX.PEFMͷϥΠϑαΠΫϧͰཧ͞ΕΔ WJFX.PEFM4DPQFͷ $PSPVUJOF#VJMEFSͰ$PSPVUJOFΛىಈ
ΤϥʔʹͳΒͳ͍Α͏ʹ͢Δ suspend fun callApi(name: String): UserResponseBody = withContext(Dispatchers.IO){ val client
= OkHttpClient() val request = Request.Builder() .url("https://api.github.com/users/$name") .build() client.newCall(request).execute().use {response -> Gson().fromJson(response.body?.string(), UserResponseBody::class.java) } } TVTQFOEؔʹ͢Δ %JTQBDIFST*0Ͱىಈ͢ΔΑ͏ʹࢦఆ
class MainViewModel : ViewModel() { val response = MutableLiveData<UserResponseBody>() val
userName = MutableLiveData<String>("sutetotanuki") val error = MutableLiveData<String>() fun getGithubUser() { viewModelScope.launch { try { response.value = callApi(userName.value ?: "") } catch (e: Throwable) { error.value = e.message } } } } Τϥʔॲཧ TVTQFOEؔͷΤϥʔ USZDBUDIͰर͑Δ
ίʔϧόοΫؔ $BMMCBDLΛ$PSPVUJOFͰͲ͏࣮͢Δͷ͔ Λ4USJQFͷ&QIFNFSBM,FZΛྫʹհ ͠·͢
ίʔϧόοΫؔ override suspend fun initSession() = suspendCoroutine<Unit> { con ->
CustomerSession.initCustomerSession( context, object : EphemeralKeyProvider { override fun createEphemeralKey( apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) { val ephemeralKeyBody = runBlocking { api.issueEphemeralKey(EphemeralKeyRequest(apiVersion)) } keyUpdateListener.onKeyUpdate(ephemeralKeyBody.string()) con.resume(Unit) } } ) }
4USJQFͷ &QIFNFSBM,FZ1SPWJEFS import androidx.annotation.Size interface EphemeralKeyProvider { fun createEphemeralKey( @Size(min
= 4) apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) }
4USJQFͷ &QIFNFSBM,FZ1SPWJEFS import androidx.annotation.Size interface EphemeralKeyProvider { fun createEphemeralKey( @Size(min
= 4) apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) } BQJ7FSTJPOΛ&QIFNFSBM,FZΛੜ͢ ΔαʔόʔαΠυͷ"1*ʹΘͨ͢ LFZ6QEBUF-JTUFOFSʹ"1*͕ੜͨ͠ &QIFNFSBM,FZΛ͢
ίʔϧόοΫؔ suspend fun initSession() = suspendCoroutine<Unit> { con -> CustomerSession.initCustomerSession(
context, object : EphemeralKeyProvider { override fun createEphemeralKey( apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) { val ephemeralKeyBody = runBlocking { api.issueEphemeralKey(EphemeralKeyRequest(apiVersion)) } keyUpdateListener.onKeyUpdate(ephemeralKeyBody.string()) con.resume(Unit) } } ) } BQJ͕TVTQFOEؔͰ࣮͞Ε͍ͯΔͷͰ SVO#MPDLJOHͰݺͼͩ͠ "1*ͷϨεϙϯεΛ-JTUFOFSʹઃఆ
ίʔϧόοΫؔ suspend fun initSession() = suspendCoroutine<Unit> { con -> CustomerSession.initCustomerSession(
context, object : EphemeralKeyProvider { override fun createEphemeralKey( apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) { val ephemeralKeyBody = runBlocking { api.issueEphemeralKey(EphemeralKeyRequest(apiVersion)) } keyUpdateListener.onKeyUpdate(ephemeralKeyBody.string()) con.resume(Unit) } } ) } -JTUFOFSʹΛͤͨͷͰ SFTVNF ෮ؼ ͢Δ
͝ਗ਼ௌ ͋Γ͕ͱ͏͍͟͝·ͨ͠