SlideShare a Scribd company logo
ProgramaçãoProgramação
Assíncrona comAssíncrona com
Kotlin CoroutinesKotlin Coroutines
2019
Lucas BorsattoLucas Borsatto
Async:Async:
Concorrência &Concorrência &
ParalelismoParalelismo
SequencialSequencial
1. CPU ociosa
2. Main Thread bloqueada
3. Congelamento do app
AsyncAsync
Exemplo:Exemplo:
Atualização de PDVsAtualização de PDVs
AbordagensAbordagens
1. Síncrona
2. Com Threads
3. Com Coroutines
SíncronoSíncrono
Síncrono - CódigoSíncrono - Código
fun getAmePrices() : List<Price> { ... }
fun getAmeProducts(): List<Product> { ... }
fun savePriceProductToStore(prices: List<Price>, products: List<Product>) { ... }
fun postNotificationToPOS(posId: Int) : Response { ... }
fun updatePosAssortment(posId): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceAndProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
ThreadsThreads
Threads - InterfaceThreads - Interface
fun thread(
start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread
Threads - CódigoThreads - Código
fun updatePosAssortment(posId: Int): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceAndProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
for(pos in posList){
thread(start=true){
updatePosAssortment(pos.posId)
}
}
Threads - FluxoThreads - Fluxo
Threads - DesvantagensThreads - Desvantagens
Quanto mais threads:
1. Maior trabalho pro SO
2. Maior consumo de memória
3. Maior tempo de CPU ociosa
CoroutinesCoroutines
Coroutines - InterfaceCoroutines - Interface
fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job (source)
Coroutines - CódigoCoroutines - Código
suspend fun getAmePrices() : List<Price> { ... }
suspend fun getAmeProducts(): List<Product> { ... }
suspend fun savePriceProductToStore(prices: List<Price>, products: List<Product>)
{ ... }
suspend fun postNotificationToPOS(posId: Int) : Response { ... }
suspend fun updatePosAssortment(posId): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
Coroutines - CódigoCoroutines - Código
runBlocking {
posList.forEach {
launch(Dispatchers.Default) {
updatePosAssortment(it.posId)
}
}
}
Coroutines - CódigoCoroutines - Código
val responses = mutableListOf<Response>()
runBlocking {
posList.map {
async(Dispatchers.IO) {
updatePosAssortment(it.posId).await()
}
}.forEach {
responses.add(it.await())
}
}
Coroutines - ProcessoCoroutines - Processo
Mas como funciona?Mas como funciona?
Continuation on Direct StyleContinuation on Direct Style
fun updatePosAssortment(posId: Int): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
Continuation on Direct StyleContinuation on Direct Style
fun updatePosAssortment(posId: Int): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
Continuation
Continuation on Direct StyleContinuation on Direct Style
fun updatePosAssortment(store): Response{
val prices = getAmePrices()
val products = getAmeProducts()
val savePriceProductToPOS(prices, products)
return postNotificationToPOS(posId)
}
Continuation
Continuation-Passing StyleContinuation-Passing Style
Continuation
fun updatePosAssortment(store): Response{
getAmePrices { prices ->
val products = getAmeProducts()
val savePriceProductToPOS(prices, products)
postNotificationToPOS(posId)
}
}
Continuation-Passing StyleContinuation-Passing Style
Continuation
fun updatePosAssortment(store): Response{
getAmePrices { prices ->
getAmeProducts { products ->
val savePriceProductToPOS(prices, products)
postNotificationToPOS(posId)
}
}
}
Continuation-Passing StyleContinuation-Passing Style
Continuation
fun updatePosAssortment(store): Response{
getAmePrices { prices ->
getAmeProducts { products ->
savePriceProductToPOS(prices, products) {
postNotificationToPOS(posId)
}
}
}
}
Continuation-Passing StyleContinuation-Passing Style
Continuation
fun updatePosAssortment(store): Response{
getAmePrices { prices ->
getAmeProducts { products ->
savePriceProductToPOS(prices, products) {
postNotificationToPOS(posId)
}
}
}
}
CPS em KotlinCPS em Kotlin
suspend fun updatePosAssortment(posId : Int): Response { ... }
Object updatePosAssortment(Int posId, Continuation<Response> cont) { ... }
Compilação JVM
Máquina de estadosMáquina de estados
suspend fun updatePosAssortment(posId: Int): Response{
//LABEL 0
val prices = getAmePrices()
//LABEL 1
val products = getAmeProducts()
//LABEL 2
val savePriceProductToPOS(prices, products)
//LABEL 3
return postNotificationToPOS(posId)
}
Máquina de estadosMáquina de estados
suspend fun updatePosAssortment(posId: Int): Response{
switch (label){
case 0:
val prices = getAmePrices()
case 1:
val products = getAmeProducts()
case 2:
val savePriceProductToPOS(prices, products)
case 3:
postNotificationToPOS(posId)
}
}
Máquina de estadosMáquina de estados
suspend fun updatePosAssortment(posId: Int): Response{
val sm = object : CoroutineImpl { ... }
switch (label){
case 0:
sm.label = 1
sm.posId = posId
val prices = getAmePrices(sm)
case 1:
val products = getAmeProducts()
case 2:
val savePriceProductToPOS(prices, products)
case 3:
postNotificationToPOS(posId)
}
}
CPU SchedulersCPU Schedulers
Pontos relevantesPontos relevantes
1. Coroutines com Java
2. Bibliotecas Java são usadas em Kotlin
3. “Coroutines are light-weight threads”
PERGUNTAS?PERGUNTAS?
TEMOS VAGASTEMOS VAGAS

More Related Content

PPTX
Arrow 101 - Kotlin funcional com Arrow
PDF
Go Containers
DOC
Virtual inheritance
PDF
[TGSA Academic Friday] How To Train Your Dragon - Intro to Modern Compiler Te...
PDF
Advanced Patterns with io.ReadWriter
PDF
Diving into byte code optimization in python
PPT
Python легко и просто. Красиво решаем повседневные задачи
PDF
Snickers: Open Source HTTP API for Media Encoding
Arrow 101 - Kotlin funcional com Arrow
Go Containers
Virtual inheritance
[TGSA Academic Friday] How To Train Your Dragon - Intro to Modern Compiler Te...
Advanced Patterns with io.ReadWriter
Diving into byte code optimization in python
Python легко и просто. Красиво решаем повседневные задачи
Snickers: Open Source HTTP API for Media Encoding

What's hot (7)

PDF
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
PDF
FPBrno 2018-05-22: Benchmarking in elixir
PDF
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
PDF
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
PDF
Om water slide
PDF
Bytes in the Machine: Inside the CPython interpreter
PDF
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
A, B, C. 1, 2, 3. Iterables you and me - Willian Martins (ebay)
FPBrno 2018-05-22: Benchmarking in elixir
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Om water slide
Bytes in the Machine: Inside the CPython interpreter
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
Ad

Similar to Programação Assíncrona com Kotlin Coroutines (20)

PDF
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
PDF
Empathic Programming - How to write comprehensible code
PDF
12.9 Program Online shopping cart (continued) (C++)This program e.pdf
PDF
COMP360 Assembler Write an assembler that reads the source code of an.pdf
PDF
How do you create a programming language for the JVM?
PDF
ES6 patterns in the wild
PDF
C++ help finish my code Phase 1 - input phase. Main reads the fi.pdf
PDF
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
PPTX
Functional programming for production quality code
PDF
Kotlin Coroutines: Let it async in
PDF
Whatnot (Re)Compose
PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
PPTX
Joy of scala
PDF
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
PPTX
Is your C# optimized
PDF
Developer Experience i TypeScript. Najbardziej ikoniczne duo
PPTX
Heap sort - Arafath Islam Sezan.pptx
PDF
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
PDF
Disassembling Go
PDF
Adopting F# at SBTech
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
Empathic Programming - How to write comprehensible code
12.9 Program Online shopping cart (continued) (C++)This program e.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdf
How do you create a programming language for the JVM?
ES6 patterns in the wild
C++ help finish my code Phase 1 - input phase. Main reads the fi.pdf
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
Functional programming for production quality code
Kotlin Coroutines: Let it async in
Whatnot (Re)Compose
Deep dive into Coroutines on JVM @ KotlinConf 2017
Joy of scala
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Is your C# optimized
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Heap sort - Arafath Islam Sezan.pptx
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
Disassembling Go
Adopting F# at SBTech
Ad

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
System and Network Administraation Chapter 3
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administration Chapter 2
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Nekopoi APK 2025 free lastest update
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
AI in Product Development-omnex systems
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
history of c programming in notes for students .pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PTS Company Brochure 2025 (1).pdf.......
System and Network Administraation Chapter 3
Odoo Companies in India – Driving Business Transformation.pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administration Chapter 2
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Nekopoi APK 2025 free lastest update
wealthsignaloriginal-com-DS-text-... (1).pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Design an Analysis of Algorithms I-SECS-1021-03
VVF-Customer-Presentation2025-Ver1.9.pptx
AI in Product Development-omnex systems
CHAPTER 2 - PM Management and IT Context
2025 Textile ERP Trends: SAP, Odoo & Oracle
history of c programming in notes for students .pptx

Programação Assíncrona com Kotlin Coroutines