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 Coroutines Flow を触ってみた話し
Search
Tomoya Miwa
September 14, 2019
Programming
900
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Kotlin Coroutines Flow を触ってみた話し
Tomoya Miwa
September 14, 2019
More Decks by Tomoya Miwa
See All by Tomoya Miwa
基礎から学ぶ大画面対応(Learning Large-Screen Support from the Ground Up)
tomoya0x00
0
8.3k
Re:VIEWで書いた「Compose で Android の edge-to-edge に対応する」をRoo Codeで発表資料にしてもらった
tomoya0x00
0
710
Compose 1.7のTextFieldはPOBox Plusで日本語変換できない
tomoya0x00
0
480
できる!ComposeでCollapsingToolbar
tomoya0x00
0
1.1k
Compose の LazyColumn パフォーマンス改善で取り組んだこと
tomoya0x00
0
2.5k
ComposeのMutableStateってどうやってLocal Unit Testすれば良いの??
tomoya0x00
0
1.3k
意外と簡単?Navigation rail導入のお話
tomoya0x00
0
1.6k
Android for Carsのお話し
tomoya0x00
1
1.1k
熟成されたアプリのmulti module化(halfway)
tomoya0x00
2
1k
Other Decks in Programming
See All in Programming
進化を続けるGo toolsの現在地 / The Current State of Ever-Evolving Go Tools
hond0413
0
210
源内ハンズオン概要編
hideg
0
180
仕様書を書く前にハーネスを作る - Agent Native開発は「探索を速く、判定を固く」
gotalab555
4
1.6k
人間の目はかわらない、だからJPEGは30年もつ
yuzneri
12
18k
プロポーザルを書いてもらう
pvcresin
0
500
これって Effect でできたのでは? / TSKaigi Mashup Kansai #2
susisu
0
240
自動化したのに回らないテスト運用の壁ーAI時代の品質責任と生産性
mfunaki
0
130
夏だ!祭りだ!祭りとはドメインモデリングでは?
ryugen04
0
270
JAWS-UG横浜 #102 AWSサ終供養LT会 成仏できない AWS サービスたち 〜本日、三体供養します〜
maroon1st
0
360
複数の Claude Code が"放置"されてしまう問題をCLI ダッシュボードを自作して解決した話
sumihiro3
1
680
2年かけて Deno に DOMMatrix を実装した話 / How I implemented DOMMatrix in Deno over two years
petamoriken
0
210
yield再入門 #phpcon
o0h
PRO
0
1.1k
Featured
See All Featured
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.6k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.3k
The untapped power of vector embeddings
frankvandijk
2
1.8k
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.7k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.7k
My Coaching Mixtape
mlcsv
0
230
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
2.1k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
10
1.3k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
SEO for Brand Visibility & Recognition
aleyda
0
4.7k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
990
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
280
Transcript
Kotlin Coroutines Flowを 触ってみた話し tomoya0x00 Coroutine ハンズオン by DroidKaigi @
LINE Fukuoka #droidkaigi_roadshow
About me tomoya0x00 Twitter, GitHub, Qiita Android, Embedded system, BLE/BT,
iOS DroidKaigi staff (since DroidKaigi 2019) DeNA Co., Ltd. Automotive Business Unit.
Kotlin Coroutines Flow is 何︖
Kotlin Coroutines Flow is 何︖ https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines- core/kotlinx.coroutines. ow/ Flow —
asynchronous cold stream of elements. RxJavaみたいなもの 最近、kotlinx-coroutines-core:1.3.0でstableになった ただし、⼀部はまだexperimentalだったりpreviewだったり @ExperimentalCoroutinesApi @FlowPreview
普通の Kotlin Coroutines との違いは︖ 基本的にCoroutinesはワンショットの⾮同期処理⽤ WebAPI呼び出しとか RxJavaのSingle/Maybe/Completableと同じ⽴ち位置 Flowは何度も値を流すストリーム⽤ 位置情報とか RxJavaのObservable/Flowableと同じ⽴ち位置
⾃分が Flow を触るモチベーション
⾃分が Flow を触るモチベーション プロダクトのコードにRxJavaとCoroutinesのコードが混在 ストリームだけ、ObservableやFlowableになっている できればCoroutinesに統⼀したい そろそろStableになったし触っておこう ちょうどプロダクトで新規機能開発がある デバイス間通信(シリアル通信)の抽象化 Androidなのか・・・︖
簡単な使い⽅
簡単な使い⽅ val myFlow = flow { // flow builderの⼀つ emit(1)
emit(2) } GlobalScope.launch { myFlow.collect { value -> println("Received $value") // Received 1 // Received 2 } }
NGな使い⽅
NGな使い⽅ suspend fun hoge() = 2 val myFlow = flow
{ emit(1) // OK withContext(Dispatchers.IO) { emit(hoge()) // NG(collectする側のコンテキストの強制指定はダメ) } } GlobalScope.launch { myFlow.collect { value -> println("Received $value") } }
こうすればOK suspend fun hoge() = 2 val myFlow = flow
{ emit(1) // OK val result = withContext(Dispatchers.IO) { hoge() } emit(result) // OK } GlobalScope.launch { myFlow.collect { value -> println("Received $value") } }
いくつかTipsや困った事
いくつかTipsや困った事 Tips collectしている間、動き続けるFlow 困った事 Operetorが少ない ConnectableObservable的なモノが無い ※間違っているのもあるかもなので、気付いたら教えて下さい
Tips collectしている間、動き続けるFlow
collectしている間、動き続けるFlow シリアル通信で受信したデータをひたすらFlowで流したい シリアル通信のread()はブロッキングI/O val received: Flow<ByteArray> = flow { coroutineScope
{ // coroutineScopeでくくると、 while (isActive) { // isActiveでキャンセルされたことが検知できる val data = withContext<ByteArray>(Dispatchers.IO) { read() } emit(data) } } }
困った事 Operetorが少ない
Operetorが少ない RxJavaに⽐べると、bufferやintervalなどOperatorに不⾜を感じる coroutineなので、⼿続き的に書けば似たようなことは実現できる Operatorに関する issue は多い
val isAvailable: Flow<Boolean> = flow { coroutineScope { while (isActive)
{ val available = withContext<Boolean>(Dispatchers.IO) { var receivedAck = false // 1sec間隔で5回pingして、1回でも応答有れば利⽤可能と判定 repeat(5) { try { delay(1000L) ping() receivedAck = true } catch (e: Exception) { // Do nothing } } receivedAck } emit(available) } } }
困った事 ConnectableFlowable的なモノが無い
ConnectableFlowable的なモノが無い RxJavaにはConnectableFlowable/Observableがある 複数のSubscriberと、同じストリームを共有できる Flowには同様な仕組みがまだ無い Issueで議論されている真っ最中 Consider sharing a Flow through
a ConnectableFlow Flow.share operator 直近はBroadcastChannelを使ってどうにかしている BroadcastChannel.asFlow()で変換してFlowとして公開
感想 まだまだOperatorが少ない RxJavaでは宣⾔的に書けていたのが、⼿続き的にかかないといけ ないので思考の切替が必要 でも、逆に⾔うと⼿続き的に書けば実現できちゃうので、そこは 良い 参考になる記事も少ない sys1yagiさんの記事がめっちゃ参考になる owOn (RxJavaで⾔うsubscribeOn)
ですらexperimental API変更はありえる
結論
まだ⼿を出すにはちょっと早いかも︖
でも、ぜひ使ってフィードバックしてい きましょう︕
ありがとうございました