Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Kotlin Coroutines Flow を触ってみた話し
Search
Tomoya Miwa
September 14, 2019
Programming
920
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Kotlin Coroutines Flow を触ってみた話し
Tomoya Miwa
September 14, 2019
Transcript
26 slides
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変更はありえる
結論
まだ⼿を出すにはちょっと早いかも︖
でも、ぜひ使ってフィードバックしてい きましょう︕
ありがとうございました
More Decks by Tomoya Miwa
See All by Tomoya Miwa
基礎から学ぶ大画面対応(Learning Large-Screen Support from the Ground Up)
tomoya0x00
0
8.7k
Re:VIEWで書いた「Compose で Android の edge-to-edge に対応する」をRoo Codeで発表資料にしてもらった
tomoya0x00
0
760
Compose 1.7のTextFieldはPOBox Plusで日本語変換できない
tomoya0x00
0
510
できる!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.7k
Android for Carsのお話し
tomoya0x00
1
1.1k
熟成されたアプリのmulti module化(halfway)
tomoya0x00
2
1.1k
Other Decks in Programming
See All in Programming
複数ドメインを一つのアプリに統合するFlutterの設計と運用_FlutterKaigi2026登壇資料(須永高弘)
takahirosunaga
0
210
クラウドエージェントは、 何がそんなに便利なのか / what makes cloud agents so useful
rkaga
5
970
はじめてのPLATEAU
nokonoko1203
1
670
SODA - FACT BOOK(EN)
sodainc
1
280
느린 네트워크와 저사양 디바이스 사용자를 위한 웹뷰 로딩 시간 개선기
kmkim
1
270
Proxmox x Talos Linux x Terraform で実現するなんかいい感じの Kubernetes クラスタ / A Sleek Kubernetes Cluster Powered by Proxmox, Talos Linux, and Terraform
nnaka2992
0
300
Getting Started with Vibe Coding
miccheng
0
250
なぜ私たちは「現時点では」KMPの導入を見送ったのか
chigichan24
1
600
プロジェクトコードをキレイキレイしよう!暗黙的な参照を読み解く静的解析
ostk0069
0
220
Ruby から Emacs を操作したい
phigasui
0
380
DroidKnights 2026 Android A2UI Jetpack Compose 기반의 안전한 AI UI 렌더링 - 박제창
itsmedreamwalker
1
260
Kawaiicon: Kubernetes, it's no longer cool, but let's secure it anyway!
barnbarn
0
140
Featured
See All Featured
Ethics towards AI in product and experience design
skipperchong
2
470
Discover your Explorer Soul
emna__ayadi
2
1.3k
We Are The Robots
honzajavorek
0
460
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
162
16k
The innovator’s Mindset - Leading Through an Era of Exponential Change - McGill University 2025
jdejongh
PRO
1
400
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
141
35k
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Well, that’s weird…
csswizardry
1
200
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
390
The Language of Interfaces
destraynor
162
27k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
1.1k
The Art of Programming - Codeland 2020
erikaheidi
57
15k