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
120
2
Share
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
310
Modularizando seu app
jcaiqueoliveira
0
75
Nova Api de Localização Android
jcaiqueoliveira
0
100
Arquitetura para android
jcaiqueoliveira
6
320
Kotlin por onde começar?
jcaiqueoliveira
1
100
Introdução ao Android
jcaiqueoliveira
1
95
Arquitetura para projetos Android
jcaiqueoliveira
1
240
Kotlin 1.1
jcaiqueoliveira
0
140
Other Decks in Technology
See All in Technology
EarthCopilotに学ぶマルチエージェントオーケストレーション
nakasho
0
300
Pure Intonation on Browser: Building a Sequencer with Ruby
nagachika
0
120
Contract One Engineering Unit 紹介資料
sansan33
PRO
0
16k
Standards et agents IA : un tour d’horizon de MCP, A2A, ADK et plus encore
glaforge
0
170
実践ハーネスエンジニアリング:TAKTで実現するAIエージェント制御 / Practical Harness Engineering: AI Agent Control Enabled by TAKT
nrslib
11
4.6k
マルチプロダクトの信頼性を効率良く保っていくために
kworkdev
PRO
0
160
コードや知識を組み込む / Incorporate Code and Knowledge
ks91
PRO
0
150
Shipping AI Agents — Lessons from Production
vvatanabe
0
240
AWS DevOps Agentはチームメイトになれるのか?/ Can AWS DevOps Agent become a teammate
kinunori
6
740
ネットワーク運用を楽にするAWS DevOps Agent活用法!! / 20260421 Masaki Okuda
shift_evolve
PRO
2
210
AIが書いたコードを信じられない問題 〜レビュー負荷を下げるために変えたこと〜 / The AI Code Trust Gap: Reducing the Review Burden
bitkey
PRO
7
1.3k
「誰一人取り残されない」 AIエージェント時代のプロダクト設計思想 Product Management Summit 2026
mizushimac
0
170
Featured
See All Featured
Git: the NoSQL Database
bkeepers
PRO
432
67k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
120
Paper Plane
katiecoart
PRO
1
49k
Building the Perfect Custom Keyboard
takai
2
730
Skip the Path - Find Your Career Trail
mkilby
1
110
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.4k
[RailsConf 2023] Rails as a piece of cake
palkan
59
6.5k
How to Talk to Developers About Accessibility
jct
2
180
The Invisible Side of Design
smashingmag
303
52k
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
130
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