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
José Caique Oliveira
June 15, 2019
Technology
2
100
Coroutines And Flow
An introduction to Kotlin Coroutines and Flow apis
José Caique Oliveira
June 15, 2019
Tweet
Share
More Decks by José Caique Oliveira
See All by José Caique Oliveira
Kotlin Flow
jcaiqueoliveira
0
110
Testing your app
jcaiqueoliveira
0
260
Modularizando seu app
jcaiqueoliveira
0
68
Nova Api de Localização Android
jcaiqueoliveira
0
71
Arquitetura para android
jcaiqueoliveira
6
310
Kotlin por onde começar?
jcaiqueoliveira
1
86
Introdução ao Android
jcaiqueoliveira
1
78
Arquitetura para projetos Android
jcaiqueoliveira
1
210
Kotlin 1.1
jcaiqueoliveira
0
120
Other Decks in Technology
See All in Technology
20241120_JAWS_東京_ランチタイムLT#17_AWS認定全冠の先へ
tsumita
2
270
OCI Network Firewall 概要
oracle4engineer
PRO
0
4.1k
データプロダクトの定義からはじめる、データコントラクト駆動なデータ基盤
chanyou0311
2
310
Incident Response Practices: Waroom's Features and Future Challenges
rrreeeyyy
0
160
いざ、BSC討伐の旅
nikinusu
2
780
Introduction to Works of ML Engineer in LY Corporation
lycorp_recruit_jp
0
120
エンジニア人生の拡張性を高める 「探索型キャリア設計」の提案
tenshoku_draft
1
130
VideoMamba: State Space Model for Efficient Video Understanding
chou500
0
190
個人でもIAM Identity Centerを使おう!(アクセス管理編)
ryder472
3
210
OCI Security サービス 概要
oracle4engineer
PRO
0
6.5k
生成AIが変えるデータ分析の全体像
ishikawa_satoru
0
130
Taming you application's environments
salaboy
0
190
Featured
See All Featured
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
126
18k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
226
22k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
131
33k
Build The Right Thing And Hit Your Dates
maggiecrowley
33
2.4k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
33
1.9k
Fireside Chat
paigeccino
34
3k
Art, The Web, and Tiny UX
lynnandtonic
297
20k
Imperfection Machines: The Place of Print at Facebook
scottboms
265
13k
RailsConf 2023
tenderlove
29
900
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
26
2.1k
What’s in a name? Adding method to the madness
productmarketing
PRO
22
3.1k
Building an army of robots
kneath
302
43k
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