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
Coroutines And Flow
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
José Caique Oliveira
June 15, 2019
Technology
130
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Coroutines And Flow
An introduction to Kotlin Coroutines and Flow apis
José Caique Oliveira
June 15, 2019
More Decks by José Caique Oliveira
See All by José Caique Oliveira
Kotlin Flow
jcaiqueoliveira
0
140
Testing your app
jcaiqueoliveira
0
320
Modularizando seu app
jcaiqueoliveira
0
86
Nova Api de Localização Android
jcaiqueoliveira
0
110
Arquitetura para android
jcaiqueoliveira
6
330
Kotlin por onde começar?
jcaiqueoliveira
1
110
Introdução ao Android
jcaiqueoliveira
1
100
Arquitetura para projetos Android
jcaiqueoliveira
1
250
Kotlin 1.1
jcaiqueoliveira
0
150
Other Decks in Technology
See All in Technology
「勝手に広まる」人気 AI エージェントを爆速で作ろう!(AWS Summit Japan 2026講演資料)
minorun365
PRO
10
2.5k
BPaaSで進むAIオペレーションの現在地 AI実装が効く領域とスケーラビリティの選定と実装
kentarofujii
0
150
AIチャット検索改善の3週間
kworkdev
PRO
2
170
From Prompt Engineering to Loop Engineering
shibuiwilliam
1
160
フルAIで個人開発して学んだあれこれ / yuruai vol.1
isaoshimizu
0
110
クラウドファンディング版StackChan 3体(4体)をインタラクティブな体験型作品にして展示もした話 / スタックチャンお誕生日会2026
you
PRO
0
180
自宅LLMの話
jacopen
1
720
Agile and AI Redmine Japan 2026
hiranabe
4
470
AWS Security Hub CSPMの成功・失敗体験
cmusudakeisuke
0
540
Bucharest Tech Week 2026 - Guardians of the Cloud-Native Galaxy
edeandrea
PRO
0
140
40代で“やっとエンジニアになれた”――閉じた学びを開き、空の青さを知る / 20260628 Naoki Takahashi
shift_evolve
PRO
4
830
レガシーな広告配信システムでのAI駆動開発/運用の挑戦
i16fujimoto
0
120
Featured
See All Featured
Test your architecture with Archunit
thirion
1
2.3k
Prompt Engineering for Job Search
mfonobong
0
350
Documentation Writing (for coders)
carmenintech
77
5.4k
Context Engineering - Making Every Token Count
addyosmani
9
980
GraphQLとの向き合い方2022年版
quramy
50
15k
Producing Creativity
orderedlist
PRO
348
40k
Designing for Performance
lara
611
70k
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
Accessibility Awareness
sabderemane
1
140
B2B Lead Gen: Tactics, Traps & Triumph
marketingsoph
0
160
Paper Plane
katiecoart
PRO
1
52k
Jess Joyce - The Pitfalls of Following Frameworks
techseoconnect
PRO
1
170
Transcript
COROUTINES AND FLOW JOSÉ CAIQUE
PROGRAM PROCESS THREADS
A PROGRAM IS A SET OF OPERATIONS TO A COMPUTER
TO PERFORM. A COMPUTER PROGRAM BECOMES A PROCESS WHEN IT IS LOADED AND BEGINS EXECUTION
A THREAD IS A SEQUENCE OF SUCH INSTRUCTIONS WITH A
PROGRAM THAT CAN BE EXECUTED INDEPENDENTLY OF OTHER CODE
COROUTINES
ESSENTIALLY, COROUTINES ARE LIGHT- WEIGHT THREADS
fun main() = runBlocking { val jobs = List(100_000) {
launch { delay(1000L) print(".") } } jobs.forEach { it.join() } } java.lang.OutOfMemoryError fun main() { val jobs = List(100_000) { thread { sleep(1000L) print(".") } } jobs.forEach { it.join() } } COROUTINES THREADS
DISPATCHERS
WHICH THREAD WILL LAUNCH THE COROUTINE
- DISPATCHERS.MAIN (ANDROID ONLY) - DISPATCHERS.DEFAULT - DISPATCHERS.IO - DISPATCHERS.UNCONFINED
fun main() { GlobalScope.launch(Main) {} GlobalScope.launch(IO) {} GlobalScope.launch(Main) {} GlobalScope.launch(Unconfined)
{} GlobalScope.launch(newSingleThreadContext("myContext")) {} }
SCOPES
DEFINE A SCOPE FOR NEW COROUTINES. USED TO PROPAGATE THE
ELEMENTS AND CANCELLATION
class MyActivity : Activity(), CoroutineScope by MainScope() { override fun
onDestroy() { cancel() } } class MyViewModel : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext = Main override fun onCleared() { super.onCleared() cancel() } } class MyViewModel : ViewModel() { init { viewModelScope.launch { ... } } }
SUSPEND FUNCTION
EXECUTION OF THE CODE WITHOUT BLOCKING THE CURRENT THREAD OF
EXECUTION. A SUSPENDING FUNCTION CANNOT BE INVOKED FROM A REGULAR CODE, BUT ONLY FROM OTHER SUSPENDING FUNCTIONS AND FROM SUSPENDING LAMBDAS
SUSPENDING FUNCTIONS DO NOT BLOCK THE CALLER THREAD. SUSPENDING FUNCTIONS
HAVE THE ABILITY TO BLOCK THE EXECUTION OF THE COROUTINE
suspend fun doRequest() : Int { return 1 } suspend
fun doRequest(): Int = withContext(IO) { 1 } //withTimeout(1000L){ ... }
suspend fun listFromApi(){ viewState.value = ScreenState.Loading viewState.value = ScreenState.Result(performRequest()) }
suspend fun doRequest(): Int = withContext(IO) { 1 }
fun retrieve() : Int { doRequest() } suspend fun doRequest():
Int = withContext(IO) { 1 //some result here } Suspend function 'performRequest' should be called only from a coroutine or another suspend function
BUILDERS
THE WAYS TO RUN A NEW COROUTINE
runBlocking{ viewState.value = ScreenState.Loading viewState.value = performRequest() } @Test fun
testSuspendingFunction() = runBlocking { val res = suspendingTask1() assertEquals(0, res) }
val job : Job = viewModelScope.launch{ viewState.value = ScreenState.Loading viewState.value
= performRequest() } //job.cancel()
val result : Deferred<T> = viewModelScope.async { viewState.value = ScreenState.Loading
viewState.value = performRequest() } result.await() //blocking result.cancel()
viewModelScope.launch(Main) { val user = withContext(IO) { userService.doLogin(username, password) }
val currentFriends = withContext(IO) { userService.requestCurrentFriends(user) } val suggestedFriends = withContext(IO) { userService.requestSuggestedFriends(user) } val finalUser = user.copy( friends = currentFriends + suggestedFriends) }
viewModelScope.launch(Main) { val user = withContext(IO) { userService.doLogin(username, password) }
val currentFriends = async(IO) { userService.requestCurrentFriends(user) } val suggestedFriends = async(IO) { userService.requestSuggestedFriends(user) } val finalUser = user.copy( friends = currentFriends + suggestedFriends) }
REMOVING CALLBACKS
suspend fun login(name: String, psw: String): User = suspendCancellableCoroutine {
continuation -> service.doLogin(username, password) { user -> continuation.resume(user) } } //continuation.resumeWithException(error)
FLOW
KOTLIN REACTIVE PROGRAMMING COLD STREAMS + COROUTINES + OPERATORS SIMILAR
TO SEQUENCES, FLOWS CAN BE TRANSFORMED USING VARIOUS COMMON OPERATORS LIKE MAP, FILTER, ETC UNLIKE A SEQUENCE, A FLOW IS ASYNCHRONOUS AND ALLOWS SUSPENDING FUNCTIONS ANYWHERE IN ITS BUILDER AND OPERATORS
fun foo(p: Params): Flow<Value> = flow { while (hasMore) emit(nextValue)
} val ints: Flow<Int> = flow { for (i in 1..10) { delay(100) emit(i) } } ints.collect { println(it) }
fun <T> Flow<T>.delayASecond() = flow { collect { value ->
// collect from the original flow delay(1000) // delay 1 second emit(value) // emit value to the resulting flow } }
YOU CAN EASILY CREATE YOUR OWN OPERATOR
val broadcast: ConflatedBroadcastChannel<User> // emitting launch { broadcast.send(mMap.getBounds()) } //
listening broadcast.consumeEach { service .retrieve(it) .map { it.getOrNull() } .collect { it?.let { … } } } //close broadcast.close()
JOSÉ CAIQUE ▸ Software Engineer ▸ Computer Science by UFS
▸ Android Tech Lead at Stone ▸ Speaker
J C A I Q U E _ J O
S E C A I Q U E J O S E C A I Q U E T H A N K S
REFERENCES ▸ http://www.inf.puc-rio.br/~roberto/docs/MCC15-04.pdf ▸ https://searchsoftwarequality.techtarget.com/definition/program ▸ https://stackoverflow.com/questions/43021816/difference-between-thread- and-coroutine-in-kotlin ▸ https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md
▸ https://kotlinlang.org/docs/reference/coroutines/basics.html ▸ https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055 ▸ https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/ kotlinx.coroutines/-coroutine-scope/ ▸ https://skillsmatter.com/skillscasts/12727-coroutines-by- example#showModal?modal-signup-complete ▸ https://antonioleiva.com/coroutines/ ▸ https://sourcediving.com/kotlin-coroutines-in-android-e2d5bb02c275 ▸ https://medium.com/@elizarov/simple-design-of-kotlin-flow-4725e7398c4c