$30 off During Our Annual Pro Sale. View Details »
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
110
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
120
Testing your app
jcaiqueoliveira
0
300
Modularizando seu app
jcaiqueoliveira
0
73
Nova Api de Localização Android
jcaiqueoliveira
0
88
Arquitetura para android
jcaiqueoliveira
6
320
Kotlin por onde começar?
jcaiqueoliveira
1
93
Introdução ao Android
jcaiqueoliveira
1
84
Arquitetura para projetos Android
jcaiqueoliveira
1
230
Kotlin 1.1
jcaiqueoliveira
0
130
Other Decks in Technology
See All in Technology
【保存版】「ガチャ」からの脱却:Gemini × Veoで作る、意図を反映するAI動画制作ワークフロー
nekoailab
0
120
AIで加速する次世代のBill Oneアーキテクチャ〜成長の先にある軌道修正〜
sansantech
PRO
1
150
ページの可視領域を算出する方法について整理する
yamatai1212
0
110
Master Dataグループ紹介資料
sansan33
PRO
1
4k
Android Studio Otter の最新 Gemini 機能 / Latest Gemini features in Android Studio Otter
yanzm
0
500
Symfony AI in Action
el_stoffel
2
250
その意思決定、まだ続けるんですか? ~痛みを超えて未来を作る、AI時代の撤退とピボットの技術~
applism118
45
25k
All About Sansan – for New Global Engineers
sansan33
PRO
1
1.3k
Introduction to Sansan, inc / Sansan Global Development Center, Inc.
sansan33
PRO
0
2.9k
How native lazy objects will change Doctrine and Symfony forever
beberlei
1
240
進化の早すぎる生成 AI と向き合う
satohjohn
0
360
今すぐGoogle Antigravityを触りましょう
rfdnxbro
0
230
Featured
See All Featured
Context Engineering - Making Every Token Count
addyosmani
9
440
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
YesSQL, Process and Tooling at Scale
rocio
174
15k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
196
68k
Site-Speed That Sticks
csswizardry
13
970
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
659
61k
Designing for humans not robots
tammielis
254
26k
Rails Girls Zürich Keynote
gr2m
95
14k
For a Future-Friendly Web
brad_frost
180
10k
Reflections from 52 weeks, 52 projects
jeffersonlam
355
21k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
32
1.8k
Six Lessons from altMBA
skipperchong
29
4.1k
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