SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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)
 

Ähnlich wie Kotlin Coroutines and Rx

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
 

Ähnlich wie Kotlin Coroutines and Rx (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
 

Mehr von Shaul Rosenzwieg

Mehr von 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
 

Kürzlich hochgeladen

Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 

Kürzlich hochgeladen (20)

Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

Kotlin Coroutines and Rx

  • 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

Hinweis der Redaktion

  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