SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Downloaden Sie, um offline zu lesen
Kotlin Coroutine - the next step
for RxJava developer?
Artur Latoszewski
Agenda:
1. Pre-Kotlin world
2. What are coroutines and why we need it
3. Theoretical knowledge
4. Basic tutorial (some code)
5. Extra examples (more code)
6. Answer for the title question
7. Where to find more information
What have we had in pre-Kotlin world?
● AsyncTasks
● Threads
Painful points:
● Android Lifecycle
● Awful API
● Callbacks
● Easy to make a bug
● Hard to debug
● Concurrency is hard
What have we had in pre-Kotlin world? - RxJava!
http://reactivex.io/
We are Kotliners!
What are Coroutines for a developer?
Coroutines allows us to write asynchronous code in
sequential way.
fun loadData() {
var data = api.getData()
showData(data)
}
sequential code
(not coroutine)
What problem does it solve?
What problem does it solve? Callbacks!
https://www.twilio.com/blog/2017/03/promises-in-swift-writing-cleaner-asynchronous-code-using-promisekit.html
RxJava problems?
Observable.just(1,2,3,4)
.map { /*someMapping*/ }
.filter { /*someFilter*/ }
.subscribe(
{ /*onNext*/ },
{ /*onError*/ }
)
RxJava problems?
Observable.just(1,2,3,4)
.map { /*someMapping*/ }
.filter { /*someFilter*/ }
.subscribe(
{ /*onNext*/ },
{ /*onError*/ }
)
Callbacks
RxJava problems?
Observable.just(1,2,3,4)
.map { /*someMapping*/ }
.filter { /*someFilter*/ }
.subscribe(
{ /*onNext*/ },
{ /*onError*/ }
)
Callbacks
Stream style
Theoretical knowledge
Coroutines - deep dive
● conceptually very light-weight threads
● one thread = ∞ coroutines
● compiled to state machine with shared state (and callbacks)
● 100K Threads = 💔, 100K Coroutines = 💚
● less context switch overhead
● less memory overhead
● works everywhere where Kotlin works
● stable since Kotlin 1.3
Suspend function
● suspend and executed later
● without blocking thread
● without changing context
● almost free
suspend fun doWorld() {
println("World!")
}
Coroutine context = Job + Dispatcher
Job (Rx ~ CompositeDisposable)
● a cancellable thing
● can’t be reused after cancel
● parent-child hierarchies
● SupervisorJob - child don’t cancel parent
Dispatchers (Rx ~ Schedulers)
● Default - thread pool = CPU cores
● Main - run on main thread (main UI thread on Android)
● IO - designed for IO tasks, share with Default
● launch() - fire and forget
○ return Job object - allows to cancel coroutine
○ uncaught exceptions = crash
● async() - promise that it will return object
○ return Deferred<out T> : Job on which we call await() to wait for result
○ without await() call it will “swallow” exception
● runBlocking() - locks current thread until end of execution
● withContext() - run internal block on specified context
Coroutine builder
Coroutines - first
launch{
println("We are in coroutine")
}
Coroutines - first
val job = GlobalScope.launch(Dispatchers.Main){
println("We are in coroutine")
}
Coroutines - cancel
val job = GlobalScope.launch(Dispatchers.Main){
println("We are in coroutine")
}
job.cancel()
------------------------------------------------------------------
RxJava disposable.dispose()
Coroutines - cancel
val job = launch (Dispatchers.Main){
while (true){
println("We are in coroutine")
}
}
job.cancel()
Coroutines - cancel
val job = launch (Dispatchers.Main){
while (isActive){
println("We are in coroutine")
}
}
job.cancel()
------------------------------------------------------------------
RxJava isDisposed()
CoroutineScope
public interface CoroutineScope {
public val coroutineContext: CoroutineContext
}
● every coroutine needs a scope (coroutine is extension method)
● scope is a lifecycle for a coroutine
● scopes creates “scope tree”
● you don’t want to use GlobalScope
CoroutineScope - Activty
class MyActivity : AppCompatActivity(), CoroutineScope {
lateinit var parentJob: SupervisorJob
override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
parentJob = SupervisorJob()
}
override fun onDestroy() {
super.onDestroy()
parentJob.cancel()
}
}
CoroutineScope - Activty
class MyActivity : AppCompatActivity(), CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob
fun buildCoroutineTree(){
launch { // MyActivity scope
async { // launch scope }
}
launch { // MyActivity scope }
}
override fun onDestroy() {
parentJob.cancel() // Cancel all coroutines in scope
}
}
CoroutineScope - ViewModel
class MyActivity : ViewModel(), CoroutineScope {
val parentJob = SupervisorJob()
override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob
override fun onCleared() {
super.onCleared()
parentJob.cancel()
}
fun doSomeStuff() {
launch{ // launch scope }
}
}
CoroutineScope - ViewModel
class MyActivity : ViewModel(), CoroutineScope {
fun doSomeStuff() {
viewModelScope.launch{ // launch scope }
}
}
● AndroidX Lifecycle v2.1.0 (alpha)
Coroutines - change context (thread)
launch (Dispatchers.Main){
println("Coroutine in main thread")
withContext(Dispatchers.IO){
println("Coroutine in background thread")
}
println("Coroutine in main thread")
}
------------------------------------------------------------------
RxJava
.observeOn()
.subscribeOn()
.unsubscribeOn()
Coroutines - sequentially
fun loadDataSequentially() {
launch(Dispatchers.Main) {
val response1 = withContext(Dispatchers.IO) { loadData1() } // 1
val response2 = withContext(Dispatchers.IO) { loadData2() } // 2
val result = response1 + response2 // 3
}
}
Coroutines - sequentially
fun loadDataSequentially() {
launch(Dispatchers.Main) {
val response1 = withContext(Dispatchers.IO) { loadData1() } // 1
val response2 = withContext(Dispatchers.IO) { loadData2() } // 2
val result = response1 + response2 // 3
}
}
Coroutines - asynchronous
launch(Dispatchers.Main) {
val response = async(Dispatchers.IO) { // Deferred<Response>
println("We are in async coroutine")
// doing stuff in background thread
loadData()
}
// doing stuff main thread
val value = response.await() // await for response
}
Coroutines - parallel
fun loadDataParallel() {
launch(Dispatchers.Main) {
val response1 = async(Dispatchers.IO) { loadData1() }
val response2 = async(Dispatchers.IO) { loadData2() }
// doing stuff main thread
val result = response1.await() + response1.await() //await for response
}
}
Coroutines - parallel
fun loadDataParallel() {
launch(Dispatchers.Main) {
val response1 = async(Dispatchers.IO) { loadData1() }
val response2 = async(Dispatchers.IO) { loadData2() }
// doing stuff main thread
val result = response1.await() + response1.await() //await for response
}
}
More complex examples
RxJava
vs
Coroutine
Dmytro Danylyk
@dmytrodanylyk
Android/Kotlin Google
Developer Expert
Operators?
Everything from Kotlin Collections (map, filter, etc.) and more:
fun loadDataWithTimeout() {
launch(Dispatchers.Main) {
val response = async(Dispatchers.IO) { loadData() }
val result = withTimeoutOrNull(2, TimeUnit.SECONDS) { response.await() }
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retry
suspend fun <T> retry(block: suspend (Int) -> T): T {
for (i in 1..5) { // try 5 times
try {
return withTimeout(500) { // with timeout
block(i)
}
} catch (e: TimeoutCancellationException) { /* retry */ }
}
return block(0) // last time just invoke without timeout
}
Retrofit
interface RemoteDataSource{
@GET("api/news")
fun getNews() : Single<NewsResponse>
}
------------------------------------------------------------------
interface RemoteDataSource {
@GET("api/news")
fun getNews(): Deferred<NewsResponse>
}
------------------------------------------------------------------
interface RemoteDataSource {
@GET("api/news")
suspend fun getNews(): NewsResponse
}
RxJava
Adapter by
JakeWharton
Retrofit 2.5.1
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Channels
● experimental
● hot observables in Rx world
● have buffer (default is 1)
● cold observables -
top issue
● cold observables ~
Sequences
val channel = Channel<Int>(1) // capacity 1
//Execution order
fun channelSend() = launch {
channel.send(1) //1
channel.send(1) //3
}
fun channelReceive() = launch {
val value1 = channel.receive() //2
val value2 = channel.receive() //4
}
Produce
val producer = produce{
send(1) //1
send(1) //3
}
fun receive() {
launch {
val value1 = producer.receive() //2
val value2 = producer.receive() //4
}
}
Actor
val subscriber = actor<Int> {
for(i in channel) {
//wait for elements in channel
}
}
fun send() {
launch {
subscriber.send(1)
subscriber.send(2)
}
}
Will it be the next step for RxJava
developer?
The next step for RxJava developer?
● Coroutines = low-level API for asynchronous calls
● Rx = observable pattern, "functional reactive programming"
● sequential vs streams, next tool in toolset
● Coroutines are faster and more memory efficient
● Perfectly replacement for Single, Completable, Maybe
● Easier to learn, lower entry threshold
● Can pass null values
● Channels can’t replace Observables
● Rx wins when dealing with real streams
● Coroutine wins with Kotlin/Native
● Rx API with Coroutines?
Should we switch to coroutines? IMHO
● You already have RxJava - stay with RxJava
● You are in love with RxJava - good
● You work with streams - only Rx
● You work with Java - Rx
● CRUD - Coroutines
● Simple app - Coroutines
● Don’t want Rx - only Coroutines
Where/What to learn more?
● https://github.com/Kotlin/kotlin-coroutines/ - core coroutine in language
● https://github.com/Kotlin/kotlinx.coroutines - base support library and other:
○ Dispatchers(“threads”) for Dispatchers.Main - Android, Spring, JavaFX
○ support for Reactive libraries - RxJava1, RxJava2, etc…
○ support for future-based libraries - JDK8, Guava, etc…
○ Kotlin/JS
○ Kotlin/Native
● KotlinConf talks about Coroutines by Roman Elizarov (2017, 2018)
Questions?
Coroutines, Kotlin, Ultimate Question of Life, the Universe,
and Everything?
@iiarchi
thecodeside.com

Weitere ähnliche Inhalte

Was ist angesagt?

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
 
Non stop random2b
Non stop random2bNon stop random2b
Non stop random2bphanhung20
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxyginecorehard_by
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcescorehard_by
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 

Was ist angesagt? (20)

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Non stop random2b
Non stop random2bNon stop random2b
Non stop random2b
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
 
Play image
Play imagePlay image
Play image
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resources
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 

Ähnlich wie Kotlin coroutine - the next step for RxJava developer?

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - CoroutineSean Tsai
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevShuhei Shogen
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewDmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting StartedTeerawat Issariyakul
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats newSerghii Chaban
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutinestdc-globalcode
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 

Ähnlich wie Kotlin coroutine - the next step for RxJava developer? (20)

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
 
Kotlin Coroutines - the new async
Kotlin Coroutines - the new asyncKotlin Coroutines - the new async
Kotlin Coroutines - the new async
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android Dev
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
 
Exploring Kotlin
Exploring KotlinExploring Kotlin
Exploring Kotlin
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Thread
ThreadThread
Thread
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 

Kürzlich hochgeladen

Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
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
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%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
 
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
 
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
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
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
 
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
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
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
 
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
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
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
 

Kürzlich hochgeladen (20)

Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
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...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%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
 
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
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
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
 
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
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
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-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS 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 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
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 🔝✔️✔️
 

Kotlin coroutine - the next step for RxJava developer?

  • 1. Kotlin Coroutine - the next step for RxJava developer? Artur Latoszewski
  • 2. Agenda: 1. Pre-Kotlin world 2. What are coroutines and why we need it 3. Theoretical knowledge 4. Basic tutorial (some code) 5. Extra examples (more code) 6. Answer for the title question 7. Where to find more information
  • 3. What have we had in pre-Kotlin world? ● AsyncTasks ● Threads Painful points: ● Android Lifecycle ● Awful API ● Callbacks ● Easy to make a bug ● Hard to debug ● Concurrency is hard
  • 4. What have we had in pre-Kotlin world? - RxJava! http://reactivex.io/
  • 6. What are Coroutines for a developer? Coroutines allows us to write asynchronous code in sequential way. fun loadData() { var data = api.getData() showData(data) } sequential code (not coroutine)
  • 7. What problem does it solve?
  • 8. What problem does it solve? Callbacks! https://www.twilio.com/blog/2017/03/promises-in-swift-writing-cleaner-asynchronous-code-using-promisekit.html
  • 9. RxJava problems? Observable.just(1,2,3,4) .map { /*someMapping*/ } .filter { /*someFilter*/ } .subscribe( { /*onNext*/ }, { /*onError*/ } )
  • 10. RxJava problems? Observable.just(1,2,3,4) .map { /*someMapping*/ } .filter { /*someFilter*/ } .subscribe( { /*onNext*/ }, { /*onError*/ } ) Callbacks
  • 11. RxJava problems? Observable.just(1,2,3,4) .map { /*someMapping*/ } .filter { /*someFilter*/ } .subscribe( { /*onNext*/ }, { /*onError*/ } ) Callbacks Stream style
  • 13. Coroutines - deep dive ● conceptually very light-weight threads ● one thread = ∞ coroutines ● compiled to state machine with shared state (and callbacks) ● 100K Threads = 💔, 100K Coroutines = 💚 ● less context switch overhead ● less memory overhead ● works everywhere where Kotlin works ● stable since Kotlin 1.3
  • 14. Suspend function ● suspend and executed later ● without blocking thread ● without changing context ● almost free suspend fun doWorld() { println("World!") }
  • 15. Coroutine context = Job + Dispatcher Job (Rx ~ CompositeDisposable) ● a cancellable thing ● can’t be reused after cancel ● parent-child hierarchies ● SupervisorJob - child don’t cancel parent Dispatchers (Rx ~ Schedulers) ● Default - thread pool = CPU cores ● Main - run on main thread (main UI thread on Android) ● IO - designed for IO tasks, share with Default
  • 16. ● launch() - fire and forget ○ return Job object - allows to cancel coroutine ○ uncaught exceptions = crash ● async() - promise that it will return object ○ return Deferred<out T> : Job on which we call await() to wait for result ○ without await() call it will “swallow” exception ● runBlocking() - locks current thread until end of execution ● withContext() - run internal block on specified context Coroutine builder
  • 17.
  • 19. Coroutines - first val job = GlobalScope.launch(Dispatchers.Main){ println("We are in coroutine") }
  • 20. Coroutines - cancel val job = GlobalScope.launch(Dispatchers.Main){ println("We are in coroutine") } job.cancel() ------------------------------------------------------------------ RxJava disposable.dispose()
  • 21. Coroutines - cancel val job = launch (Dispatchers.Main){ while (true){ println("We are in coroutine") } } job.cancel()
  • 22. Coroutines - cancel val job = launch (Dispatchers.Main){ while (isActive){ println("We are in coroutine") } } job.cancel() ------------------------------------------------------------------ RxJava isDisposed()
  • 23. CoroutineScope public interface CoroutineScope { public val coroutineContext: CoroutineContext } ● every coroutine needs a scope (coroutine is extension method) ● scope is a lifecycle for a coroutine ● scopes creates “scope tree” ● you don’t want to use GlobalScope
  • 24. CoroutineScope - Activty class MyActivity : AppCompatActivity(), CoroutineScope { lateinit var parentJob: SupervisorJob override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) parentJob = SupervisorJob() } override fun onDestroy() { super.onDestroy() parentJob.cancel() } }
  • 25. CoroutineScope - Activty class MyActivity : AppCompatActivity(), CoroutineScope { override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob fun buildCoroutineTree(){ launch { // MyActivity scope async { // launch scope } } launch { // MyActivity scope } } override fun onDestroy() { parentJob.cancel() // Cancel all coroutines in scope } }
  • 26. CoroutineScope - ViewModel class MyActivity : ViewModel(), CoroutineScope { val parentJob = SupervisorJob() override val coroutineContext: CoroutineContext = Dispatchers.Main + parentJob override fun onCleared() { super.onCleared() parentJob.cancel() } fun doSomeStuff() { launch{ // launch scope } } }
  • 27. CoroutineScope - ViewModel class MyActivity : ViewModel(), CoroutineScope { fun doSomeStuff() { viewModelScope.launch{ // launch scope } } } ● AndroidX Lifecycle v2.1.0 (alpha)
  • 28. Coroutines - change context (thread) launch (Dispatchers.Main){ println("Coroutine in main thread") withContext(Dispatchers.IO){ println("Coroutine in background thread") } println("Coroutine in main thread") } ------------------------------------------------------------------ RxJava .observeOn() .subscribeOn() .unsubscribeOn()
  • 29. Coroutines - sequentially fun loadDataSequentially() { launch(Dispatchers.Main) { val response1 = withContext(Dispatchers.IO) { loadData1() } // 1 val response2 = withContext(Dispatchers.IO) { loadData2() } // 2 val result = response1 + response2 // 3 } }
  • 30. Coroutines - sequentially fun loadDataSequentially() { launch(Dispatchers.Main) { val response1 = withContext(Dispatchers.IO) { loadData1() } // 1 val response2 = withContext(Dispatchers.IO) { loadData2() } // 2 val result = response1 + response2 // 3 } }
  • 31. Coroutines - asynchronous launch(Dispatchers.Main) { val response = async(Dispatchers.IO) { // Deferred<Response> println("We are in async coroutine") // doing stuff in background thread loadData() } // doing stuff main thread val value = response.await() // await for response }
  • 32. Coroutines - parallel fun loadDataParallel() { launch(Dispatchers.Main) { val response1 = async(Dispatchers.IO) { loadData1() } val response2 = async(Dispatchers.IO) { loadData2() } // doing stuff main thread val result = response1.await() + response1.await() //await for response } }
  • 33. Coroutines - parallel fun loadDataParallel() { launch(Dispatchers.Main) { val response1 = async(Dispatchers.IO) { loadData1() } val response2 = async(Dispatchers.IO) { loadData2() } // doing stuff main thread val result = response1.await() + response1.await() //await for response } }
  • 36. Operators? Everything from Kotlin Collections (map, filter, etc.) and more: fun loadDataWithTimeout() { launch(Dispatchers.Main) { val response = async(Dispatchers.IO) { loadData() } val result = withTimeoutOrNull(2, TimeUnit.SECONDS) { response.await() } }
  • 37. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 38. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 39. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 40. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 41. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 42. Retry suspend fun <T> retry(block: suspend (Int) -> T): T { for (i in 1..5) { // try 5 times try { return withTimeout(500) { // with timeout block(i) } } catch (e: TimeoutCancellationException) { /* retry */ } } return block(0) // last time just invoke without timeout }
  • 43. Retrofit interface RemoteDataSource{ @GET("api/news") fun getNews() : Single<NewsResponse> } ------------------------------------------------------------------ interface RemoteDataSource { @GET("api/news") fun getNews(): Deferred<NewsResponse> } ------------------------------------------------------------------ interface RemoteDataSource { @GET("api/news") suspend fun getNews(): NewsResponse } RxJava Adapter by JakeWharton Retrofit 2.5.1
  • 44. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 45. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 46. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 47. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 48. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 49. Channels ● experimental ● hot observables in Rx world ● have buffer (default is 1) ● cold observables - top issue ● cold observables ~ Sequences val channel = Channel<Int>(1) // capacity 1 //Execution order fun channelSend() = launch { channel.send(1) //1 channel.send(1) //3 } fun channelReceive() = launch { val value1 = channel.receive() //2 val value2 = channel.receive() //4 }
  • 50. Produce val producer = produce{ send(1) //1 send(1) //3 } fun receive() { launch { val value1 = producer.receive() //2 val value2 = producer.receive() //4 } }
  • 51. Actor val subscriber = actor<Int> { for(i in channel) { //wait for elements in channel } } fun send() { launch { subscriber.send(1) subscriber.send(2) } }
  • 52. Will it be the next step for RxJava developer?
  • 53. The next step for RxJava developer? ● Coroutines = low-level API for asynchronous calls ● Rx = observable pattern, "functional reactive programming" ● sequential vs streams, next tool in toolset ● Coroutines are faster and more memory efficient ● Perfectly replacement for Single, Completable, Maybe ● Easier to learn, lower entry threshold ● Can pass null values ● Channels can’t replace Observables ● Rx wins when dealing with real streams ● Coroutine wins with Kotlin/Native ● Rx API with Coroutines?
  • 54. Should we switch to coroutines? IMHO ● You already have RxJava - stay with RxJava ● You are in love with RxJava - good ● You work with streams - only Rx ● You work with Java - Rx ● CRUD - Coroutines ● Simple app - Coroutines ● Don’t want Rx - only Coroutines
  • 55. Where/What to learn more? ● https://github.com/Kotlin/kotlin-coroutines/ - core coroutine in language ● https://github.com/Kotlin/kotlinx.coroutines - base support library and other: ○ Dispatchers(“threads”) for Dispatchers.Main - Android, Spring, JavaFX ○ support for Reactive libraries - RxJava1, RxJava2, etc… ○ support for future-based libraries - JDK8, Guava, etc… ○ Kotlin/JS ○ Kotlin/Native ● KotlinConf talks about Coroutines by Roman Elizarov (2017, 2018)
  • 56. Questions? Coroutines, Kotlin, Ultimate Question of Life, the Universe, and Everything? @iiarchi thecodeside.com