SlideShare une entreprise Scribd logo
1  sur  48
Kotlin coroutines and Rx
Shaul Rosenzweig
Fullstack as a
service
- I am part of Tikal's Android group. We
meet, share, contribute and code
together on a monthly basis… We have
Tech radar, FuseDays, weekly lightning
talks, monthly meetups...
WHO AM I?
- Coding since 1980es
WHO AM I ?
Professional coding since late 1990es,
mobile since 2001, PalmOS, WinCE,
Symbian, Brew, J2ME, and Android
since 2009
Currently working in Cellebrite,
working on an application 100%
written in Kotlin, using Reactive,
Dagger, etc.
Why not switch to Kotlin?
We have always done it this way
James Gosling has a nicer beard than
Jake Wharton
Nobody died from boilerplate, you
spoilt brat!
WE ARE USED TO JAVA
OUR CODEBASE IS IN JAVA
PRODUCES SAME BYTECODE
PERSONAL PREFERENCE
PRO: For switching
LESS BOILERPLATE-> LESS BUGS
NULL SAFETY, etc
CAN BE ARGUED BOTH WAYS
KNOCKOUT BLOW: COROUTINES
FASTER EXECUTING CODE
SMALLER MEMORY FOOTPRINT
TAILOR MADE FOR REACTIVE
Regular synchronous query
fun query(): List<CallLogDao> {
val cursor = context.contentResolver.query(
CallLog.Calls.CONTENT_URI
null, null, null, null)
return queryAllLogs(cursor)
}
Reactive with SQL Brite
fun queryRxSqbrite(): Observable<List<CallLogDao>> {
return sqBriteResolver.createQuery(
CallLog.Calls.CONTENT_URI,
null, null, null, null, false)
.mapToList({
c -> CallLogDao(c)
}).firstElement().toObservable()
}
Consuming rx Observable
@Test
fun testRxSqBrite() {
val latch = CountDownLatch(1)
var gotList = ArrayList<CallLogDao> ()
manager.queryRxSqbrite().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
list: List<CallLogDao> ->
gotList.addAll( list)
latch.countDown()
})
latch.await()
assertTrue("got some logs", gotList.size > 0)
}
What are coroutines?
Light weight way of asynchronously execute
computations that can be suspended without
blocking the thread
How are they different than
threads?
● Much lighter than threads
● Suspending is not blocking
● Millions of coroutines can run in one thread
● Less context switch overhead
● Less memory overhead
Trivial example
suspend fun doALongQuery() { … }
suspend fun processResults() { … }
suspend fun uploadResultsToServer() { … }
fun saveSessionStatus(status) { … }
suspend fun doALotOfWork() {
val queryResult = doALongQuery()
val processedResults = processResults(queryResult)
val status = uploadResultsToServer(processedResults)
saveSessionStatus(status)
}
Coroutine builder
fun doALotOfWork() {
launch(UI) {
val queryResult = doALongQuery()
val processedResults = processResults(queryResult)
val status = uploadResultsToServer(processedResults)
saveSessionStatus(status)
}
}
Async with Anko coroutines
fun queryAsyncAnko() : Deferred<List<CallLogDao>>? {
val cursor = context.contentResolver.query(
CallLog.Calls.CONTENT_URI,
null, null, null, null)
return bg {
queryAllLogs(cursor)
}
} else {
return null
}
}
Consuming Anko deferred
@Test
fun testAsyncAnko() {
val deferredLogs = manager.queryAsyncAnko()
assertNotNull("is it null", deferredLogs?.await())
assertTrue("got some?", actualLogs!!.size > 0)
}
How do coroutines work?
Not a new JVM feature, implemented via compile
time bytecode changes.
Code turned into a state machine
When compiling, suspension points are inserted
into the code.
When suspended, state and variables are saved
and serialized.
Suspended coroutine is called continuation.
IDE support
In Kotlin 1.2 they are opt-in
alpha feature
But ready for production
Async with Kotlin coroutines
suspend fun queryAsyncCoroutines(): Job? {
val cursor = context.contentResolver.query(
CallLog.Calls.CONTENT_URI,
null, null, null, null)
try {
job = launch(CommonPool) {
queryAllLogs(cursor, selection, selectionArgs)
}
} finally {
return job
}
}
What about Rx?
● Experimental lib, kotlinx coroutines reactive
● Wrappers for Reactive Streams, Reactor,
RxJava 1.x and RxJava 2.x using coroutines
● Under heavy development, and very
experimental
● At the time of writing, version is 0.18
Current status
IMPORTANT NOTE: We advise library authors to follow the
same convention: add the "experimental" (e.g.
com.example.experimental) suffix to your packages exposing
coroutine-based APIs so that your library remains binary
compatible. When the final API is released, follow these steps:
Rx2 example: flowable
return rxFlowable(coroutineContext) {
if (cursor.moveToFirst()) {
do {
send(CallLogDao(cursor))
} while (cursor.moveToNext())
}
}
Consuming rx2 Flowable
@Test
fun testRx2Coroutines() = runBlocking {
val source = manager.queryRxCoroutines(coroutineContext)
if (source != null) {
var success = false
source.observeOn(Schedulers.io(), false, 10)
.doOnComplete {
success = true
}
.subscribe {
log -> Log.d(TAG, "got " + log.toString())
} }
source.awaitLast()
assertTrue("got published via RX", success)
} else {
assertTrue("failed to generate RX stream", false)
}
}
But what is this coroutineContext?
Most important part is that they include a
coroutine dispatcher which determines on what
threads can the coroutine be executed.
They can be specified, or parent context can be
used.
Coroutine children
When a croutine is launched with context of
another coroutine, it becomes its child.
When a parent is cancelled, all of its children are
cancelled.
Waiting in coroutine context
If Thread.sleep(), CountdownLatch or similar
mechanism is used, it blocks the thread,
therefore coroutine does not get executed.
Instead use suspending, such as await, delay, or
similar.
We have seen the future
Not only for Android
Backend, Frontend, Mobile
and DevOps: Kotlin is fullstack
Links
● https://github.com/MaTriXy/mobileEvent-rx-kotlin
● https://github.com/Kotlin/kotlin-coroutines/
● https://github.com/Kotlin/kotlinx.coroutines/
● https://kotlin.github.io/kotlinx.coroutines/
● https://kotlinlang.org/docs/reference/coroutines.html
● https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
● https://github.com/Kotlin/anko/wiki/Anko-Coroutines
● Talk by Andrey Breslav
● Talk by Roman Elizarov
● Talk by Svetlana Isakova
THANK YOU
THANK YOU
Shaul Rosenzweig
Email: shaulr@tikalk.com
Tel: +972-52-644-5240

Contenu connexe

Tendances

Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaPratama Nur Wijaya
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerIslam Sharabash
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesVadims Savjolovs
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.jsPiotr Pelczar
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsNodeXperts
 
Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Love Nyberg
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Fine grain process control 2nd nov
Fine grain process control 2nd novFine grain process control 2nd nov
Fine grain process control 2nd novSurendraGangarapu1
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Red Hat Developers
 
'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)Gary Trakhman
 

Tendances (20)

Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
Async java8
Async java8Async java8
Async java8
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Loops
LoopsLoops
Loops
 
Pharos
PharosPharos
Pharos
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Fine grain process control 2nd nov
Fine grain process control 2nd novFine grain process control 2nd nov
Fine grain process control 2nd nov
 
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
 
'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)
 

Similaire à Kotlin coroutines and Rx: LESS BOILERPLATE-> LESS BUGS

Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Davide Cerbo
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9Marcus Lagergren
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
The State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMThe State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMVolkan Yazıcı
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-CNissan Tsafrir
 
State management in a GraphQL era
State management in a GraphQL eraState management in a GraphQL era
State management in a GraphQL erakristijanmkd
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 

Similaire à Kotlin coroutines and Rx: LESS BOILERPLATE-> LESS BUGS (20)

Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
The State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMThe State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVM
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Exploring Kotlin
Exploring KotlinExploring Kotlin
Exploring Kotlin
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
State management in a GraphQL era
State management in a GraphQL eraState management in a GraphQL era
State management in a GraphQL era
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 

Plus de Shaul Rosenzwieg

Plus de Shaul Rosenzwieg (8)

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a pro
 
Android Open Accessory
Android Open AccessoryAndroid Open Accessory
Android Open Accessory
 
Lifecycle of a pixel
Lifecycle of a pixelLifecycle of a pixel
Lifecycle of a pixel
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android Development
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internals
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 

Dernier

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 

Dernier (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 

Kotlin coroutines and Rx: LESS BOILERPLATE-> LESS BUGS

  • 1. Kotlin coroutines and Rx Shaul Rosenzweig Fullstack as a service
  • 2. - I am part of Tikal's Android group. We meet, share, contribute and code together on a monthly basis… We have Tech radar, FuseDays, weekly lightning talks, monthly meetups... WHO AM I?
  • 3. - Coding since 1980es WHO AM I ?
  • 4. Professional coding since late 1990es, mobile since 2001, PalmOS, WinCE, Symbian, Brew, J2ME, and Android since 2009
  • 5. Currently working in Cellebrite, working on an application 100% written in Kotlin, using Reactive, Dagger, etc.
  • 6. Why not switch to Kotlin?
  • 7. We have always done it this way
  • 8. James Gosling has a nicer beard than Jake Wharton
  • 9. Nobody died from boilerplate, you spoilt brat!
  • 10. WE ARE USED TO JAVA
  • 11. OUR CODEBASE IS IN JAVA
  • 17. CAN BE ARGUED BOTH WAYS
  • 21. TAILOR MADE FOR REACTIVE
  • 22. Regular synchronous query fun query(): List<CallLogDao> { val cursor = context.contentResolver.query( CallLog.Calls.CONTENT_URI null, null, null, null) return queryAllLogs(cursor) }
  • 23. Reactive with SQL Brite fun queryRxSqbrite(): Observable<List<CallLogDao>> { return sqBriteResolver.createQuery( CallLog.Calls.CONTENT_URI, null, null, null, null, false) .mapToList({ c -> CallLogDao(c) }).firstElement().toObservable() }
  • 24. Consuming rx Observable @Test fun testRxSqBrite() { val latch = CountDownLatch(1) var gotList = ArrayList<CallLogDao> () manager.queryRxSqbrite().subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ list: List<CallLogDao> -> gotList.addAll( list) latch.countDown() }) latch.await() assertTrue("got some logs", gotList.size > 0) }
  • 25. What are coroutines? Light weight way of asynchronously execute computations that can be suspended without blocking the thread
  • 26. How are they different than threads? ● Much lighter than threads ● Suspending is not blocking ● Millions of coroutines can run in one thread ● Less context switch overhead ● Less memory overhead
  • 27. Trivial example suspend fun doALongQuery() { … } suspend fun processResults() { … } suspend fun uploadResultsToServer() { … } fun saveSessionStatus(status) { … } suspend fun doALotOfWork() { val queryResult = doALongQuery() val processedResults = processResults(queryResult) val status = uploadResultsToServer(processedResults) saveSessionStatus(status) }
  • 28. Coroutine builder fun doALotOfWork() { launch(UI) { val queryResult = doALongQuery() val processedResults = processResults(queryResult) val status = uploadResultsToServer(processedResults) saveSessionStatus(status) } }
  • 29. Async with Anko coroutines fun queryAsyncAnko() : Deferred<List<CallLogDao>>? { val cursor = context.contentResolver.query( CallLog.Calls.CONTENT_URI, null, null, null, null) return bg { queryAllLogs(cursor) } } else { return null } }
  • 30. Consuming Anko deferred @Test fun testAsyncAnko() { val deferredLogs = manager.queryAsyncAnko() assertNotNull("is it null", deferredLogs?.await()) assertTrue("got some?", actualLogs!!.size > 0) }
  • 31. How do coroutines work? Not a new JVM feature, implemented via compile time bytecode changes.
  • 32. Code turned into a state machine When compiling, suspension points are inserted into the code. When suspended, state and variables are saved and serialized. Suspended coroutine is called continuation.
  • 34. In Kotlin 1.2 they are opt-in alpha feature
  • 35. But ready for production
  • 36. Async with Kotlin coroutines suspend fun queryAsyncCoroutines(): Job? { val cursor = context.contentResolver.query( CallLog.Calls.CONTENT_URI, null, null, null, null) try { job = launch(CommonPool) { queryAllLogs(cursor, selection, selectionArgs) } } finally { return job } }
  • 37. What about Rx? ● Experimental lib, kotlinx coroutines reactive ● Wrappers for Reactive Streams, Reactor, RxJava 1.x and RxJava 2.x using coroutines ● Under heavy development, and very experimental ● At the time of writing, version is 0.18
  • 38. Current status IMPORTANT NOTE: We advise library authors to follow the same convention: add the "experimental" (e.g. com.example.experimental) suffix to your packages exposing coroutine-based APIs so that your library remains binary compatible. When the final API is released, follow these steps:
  • 39. Rx2 example: flowable return rxFlowable(coroutineContext) { if (cursor.moveToFirst()) { do { send(CallLogDao(cursor)) } while (cursor.moveToNext()) } }
  • 40. Consuming rx2 Flowable @Test fun testRx2Coroutines() = runBlocking { val source = manager.queryRxCoroutines(coroutineContext) if (source != null) { var success = false source.observeOn(Schedulers.io(), false, 10) .doOnComplete { success = true } .subscribe { log -> Log.d(TAG, "got " + log.toString()) } } source.awaitLast() assertTrue("got published via RX", success) } else { assertTrue("failed to generate RX stream", false) } }
  • 41. But what is this coroutineContext? Most important part is that they include a coroutine dispatcher which determines on what threads can the coroutine be executed. They can be specified, or parent context can be used.
  • 42. Coroutine children When a croutine is launched with context of another coroutine, it becomes its child. When a parent is cancelled, all of its children are cancelled.
  • 43. Waiting in coroutine context If Thread.sleep(), CountdownLatch or similar mechanism is used, it blocks the thread, therefore coroutine does not get executed. Instead use suspending, such as await, delay, or similar.
  • 44. We have seen the future
  • 45. Not only for Android
  • 46. Backend, Frontend, Mobile and DevOps: Kotlin is fullstack
  • 47. Links ● https://github.com/MaTriXy/mobileEvent-rx-kotlin ● https://github.com/Kotlin/kotlin-coroutines/ ● https://github.com/Kotlin/kotlinx.coroutines/ ● https://kotlin.github.io/kotlinx.coroutines/ ● https://kotlinlang.org/docs/reference/coroutines.html ● https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html ● https://github.com/Kotlin/anko/wiki/Anko-Coroutines ● Talk by Andrey Breslav ● Talk by Roman Elizarov ● Talk by Svetlana Isakova
  • 48. THANK YOU THANK YOU Shaul Rosenzweig Email: shaulr@tikalk.com Tel: +972-52-644-5240

Notes de l'éditeur

  1. With or without callback Thread = 2mb RAM - 100 threads 10 000 threads Callback hell Error handling
  2. Rx - essentially future/promise
  3. No callback hell composable , propagates exceptions, but has combinators, different names diff libs
  4. Suspension points Same as blocking code Loops Can use high order functions like forEach no need for combinators
  5. Interface between regular and suspending world Returns immidatley
  6. Using async coroutine builder Returning deferred future
  7. Androidstudio 3 Marks suspension points
  8. Send will send on thread as specified in observeOn