Slide 1

Slide 1 text

RxJava & Coroutines A Practical Analysis Droidcon Lisbon ! @askashdavies

Slide 2

Slide 2 text

@askashdavies

Slide 3

Slide 3 text

@askashdavies

Slide 4

Slide 4 text

pusher.com/state-of-kotlin

Slide 5

Slide 5 text

blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/

Slide 6

Slide 6 text

Coroutines @askashdavies

Slide 7

Slide 7 text

fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") Thread.sleep(2000L) } // Hello, // World! @askashdavies

Slide 8

Slide 8 text

fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") Thread.sleep(2000L) } // Hello, // World! @askashdavies

Slide 9

Slide 9 text

fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") Thread.sleep(2000L) } // Hello, // World! @askashdavies

Slide 10

Slide 10 text

Coroutine Builders @askashdavies

Slide 11

Slide 11 text

Coroutine Builders val deferred: Deferred = async { "Hello World!" } @askashdavies

Slide 12

Slide 12 text

Coroutine Builders val deferred: Deferred = async { "Hello World!" } val result: String = deferred.await() @askashdavies

Slide 13

Slide 13 text

Coroutine Builders val deferred: Deferred = async { "Hello World!" } val result: String = deferred.await() val job: Job = launch { "Hello World!" } @askashdavies

Slide 14

Slide 14 text

Coroutine Builders val deferred: Deferred = async { "Hello World!" } val result: String = deferred.await() val job: Job = launch { "Hello World!" } job.join() @askashdavies

Slide 15

Slide 15 text

⚖ Stability @askashdavies

Slide 16

Slide 16 text

@askashdavies

Slide 17

Slide 17 text

@Annotations ( ! Here be dragons) @askashdavies

Slide 18

Slide 18 text

Annotations @ExperimentalCoroutinesApi // @askashdavies

Slide 19

Slide 19 text

Annotations @ExperimentalCoroutinesApi // @FlowPreview // ⚠ @askashdavies

Slide 20

Slide 20 text

Annotations @ExperimentalCoroutinesApi // @FlowPreview // ⚠ @ObsoleteCoroutinesApi // ⚠ @askashdavies

Slide 21

Slide 21 text

Annotations @ExperimentalCoroutinesApi // @FlowPreview // ⚠ @ObsoleteCoroutinesApi // ⚠ @InternalCoroutinesApi // ☠ @askashdavies

Slide 22

Slide 22 text

Annotations @Experimental @askashdavies

Slide 23

Slide 23 text

! Coroutines @askashdavies

Slide 24

Slide 24 text

! Native first-party library @askashdavies

Slide 25

Slide 25 text

! Easy-to-use @askashdavies

Slide 26

Slide 26 text

! suspend fun @askashdavies

Slide 27

Slide 27 text

Dispatchers » Default » IO » Main » Android (Main Thread Dispatcher) » JavaFx (Application Thread Dispatcher) » Swing (Event Dispatcher Thread) » Unconfined @askashdavies

Slide 28

Slide 28 text

! History of Android @askashdavies

Slide 29

Slide 29 text

Background Processes @askashdavies

Slide 30

Slide 30 text

Background Processes ! Runnable / Handler @askashdavies

Slide 31

Slide 31 text

Background Processes ! AsyncTask @askashdavies

Slide 32

Slide 32 text

Background Processes ! IntentService @askashdavies

Slide 33

Slide 33 text

Background Processes ! Loader @askashdavies

Slide 34

Slide 34 text

Background Processes WorkManager @askashdavies

Slide 35

Slide 35 text

! @askashdavies

Slide 36

Slide 36 text

xkcd.com/927/

Slide 37

Slide 37 text

RxJava to the rescue @askashdavies

Slide 38

Slide 38 text

⛓ Chained operations @askashdavies

Slide 39

Slide 39 text

⬆ ⬇ Abstract threading @askashdavies

Slide 40

Slide 40 text

! Reactive @askashdavies

Slide 41

Slide 41 text

@askashdavies

Slide 42

Slide 42 text

@askashdavies

Slide 43

Slide 43 text

@askashdavies

Slide 44

Slide 44 text

@askashdavies

Slide 45

Slide 45 text

@askashdavies

Slide 46

Slide 46 text

! Asynchronous APIs Synchronous APIs @askashdavies

Slide 47

Slide 47 text

@askashdavies

Slide 48

Slide 48 text

! Observable .fromIterable(resourceDraft.getResources()) .flatMap(resourceServiceApiClient::createUploadContainer) .zipWith(Observable.fromIterable(resourceDraft.getResources()), Pair::create) .flatMap(uploadResources()) .toList() .toObservable() .flatMapMaybe(resourceCache.getResourceCachedItem()) .defaultIfEmpty(Resource.getDefaultItem()) .flatMap(postResource(resourceId, resourceDraft.getText(), currentUser, resourceDraft.getIntent())) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( resource -> repository.setResource(resourceId, resource, provisionalResourceId), resourceUploadError(resourceId, resourceDraft, provisionalResourceId) ); @askashdavies

Slide 49

Slide 49 text

Anchorman: The Legend of Ron Burgundy (DreamWorks Pictures)

Slide 50

Slide 50 text

⚙ Hidden complexity @askashdavies

Slide 51

Slide 51 text

! Hidden gotchas @askashdavies

Slide 52

Slide 52 text

! Memory footprint @askashdavies

Slide 53

Slide 53 text

⤴ Steep learning curve @askashdavies

Slide 54

Slide 54 text

@askashdavies

Slide 55

Slide 55 text

#RxMustDie pca.st/7IJG @askashdavies

Slide 56

Slide 56 text

"If all you have is a hammer, everything looks like a nail" — Abraham Maslow, The Psychology of Science, 1966 @askashdavies

Slide 57

Slide 57 text

Coroutine Use Cases @askashdavies

Slide 58

Slide 58 text

Network Call Handling // RxJava2: Single fun getUser(): Single = Single.fromCallable { /* ... */ } // Coroutines: T suspend fun getUser(): User = /* ... */ @askashdavies

Slide 59

Slide 59 text

Cache Retrieval // RxJava2: Maybe fun getUser(): Maybe = Maybe.fromCallable { /* ... */ } // Coroutines: T? suspend fun getUser(): User? = /* ... */ @askashdavies

Slide 60

Slide 60 text

Background Task Handling // RxJava2: Completable fun storeUser(user: User): Completable.fromCallable { /* ... */ } // Coroutines: Unit suspend fun storeUser(user: User) { /* ... */ } @askashdavies

Slide 61

Slide 61 text

Thread Handling // RxJava2 getUser() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { /* Do something */ } // Coroutines launch(Dispatchers.Main) { withContext(Dispatchers.IO) { val user = getUser() /* Do something */ } } @askashdavies

Slide 62

Slide 62 text

! FlatMap // RxJava2 getUser() .flatMap { doSomethingWithUser(it) } .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { /* Do something else */ } // Coroutines launch(Dispatchers.Main) { val user = getUser() val smth = doSomethingWithUser(user) /* Do something else */ } @askashdavies

Slide 63

Slide 63 text

Callback Consumption // RxJava2 fun getSingle(): Single = Single.create { emitter -> doSomethingAsync(object: Callback { override fun onComplete(result: T) = emitter.onSuccess(result) override fun onException(exception: Exception) = emitter.onError(exception) }) } // Coroutines suspend fun getCoroutine() : T = suspendCoroutine { continuation -> doSomethingAsync(object : Callback { override fun onComplete(result: T) = continuation.resume(result) override fun onException(exception: Exception) = continuation.resumeWithException(exception) }) } @askashdavies

Slide 64

Slide 64 text

Task Cancellation // RxJava2 val disposable: Disposable = Single .create { /* Do something */ } .subscribe { /* Do something else */ } disposable.dispose() // Coroutine val parent: Job = Job() launch(Dispatchers.Main + parent) { /* Do something */ } parent.cancelChildren() @askashdavies

Slide 65

Slide 65 text

! Backpressure @askashdavies

Slide 66

Slide 66 text

! Backpressure launch { channel.send("Hello") } @askashdavies

Slide 67

Slide 67 text

ViewModel.viewModelScope androidx.lifecycle:2.1.0 @askashdavies

Slide 68

Slide 68 text

Channels @askashdavies

Slide 69

Slide 69 text

Roman Elizarov Cold flows, hot channels flow { emit("Hello") emit("World") } medium.com/@elizarov/cold-flows-hot-channels-d74769805f9

Slide 70

Slide 70 text

Flow ! Observable.create { emitter: ObservableEmitter -> emitter.onNext("Hello") emitter.onNext("World") } @askashdavies

Slide 71

Slide 71 text

Flow ! flow { collector: FlowCollector -> collector.emit("Hello") collector.emit("World") } @askashdavies

Slide 72

Slide 72 text

Flow ! flow { emit("Hello world") } .onEach { delay(500) } .map { it.length } .collect { println("Length: $it") } @askashdavies

Slide 73

Slide 73 text

Testing @Test fun testFoo() = runBlockingTest { val actual = foo() // ... } suspend fun foo() { delay(1_000) // ... } github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test

Slide 74

Slide 74 text

runBlockingTest » Auto-advancing of time ⏱⏩ » Explicit time control # » Eager execution of launch or async » Pause, manually advance, and restart execution » Report uncaught exceptions as test failures @askashdavies

Slide 75

Slide 75 text

⚙ RxJava: Complex Business Logic @askashdavies

Slide 76

Slide 76 text

Asynchronicity Comparison Manuel Vivo (@manuelvicnt) medium.com/capital-one-tech/coroutines-and-rxjava-an-asynchronicity-comparison-part-1-asynchronous-programming-e726a925342a

Slide 77

Slide 77 text

Is Coroutines a replacement for RxJava? @askashdavies

Slide 78

Slide 78 text

Maybe... @askashdavies

Slide 79

Slide 79 text

Should I migrate to Coroutines? @askashdavies

Slide 80

Slide 80 text

Probably not... @askashdavies

Slide 81

Slide 81 text

"If it ain't broke, don't fix it" — Bert Lance, Nation's Business, 1977 @askashdavies

Slide 82

Slide 82 text

© 2019 Viacom International Inc.

Slide 83

Slide 83 text

Did "you" migrate to Coroutines? @askashdavies

Slide 84

Slide 84 text

@askashdavies

Slide 85

Slide 85 text

How could I migrate to Coroutines? @askashdavies

Slide 86

Slide 86 text

! Migration Policy @askashdavies

Slide 87

Slide 87 text

Retrofit Services @askashdavies

Slide 88

Slide 88 text

Retrofit 2.6.0 Built-in suspend support github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05

Slide 89

Slide 89 text

interface UserService { @GET("/user") suspend fun getUser(): User } GlobalScope.launch { val user = retrofit .create() // >= 2.5.0 .getUser() } @askashdavies

Slide 90

Slide 90 text

Coroutines RxJava2 org.jetbrains.kotlinx:kotlinx-coroutines-rx2:+ @askashdavies

Slide 91

Slide 91 text

Name Scope Description rxCompletable CoroutineScope Cold completable that starts coroutine on subscribe rxMaybe CoroutineScope Cold maybe that starts coroutine on subscribe rxSingle CoroutineScope Cold single that starts coroutine on subscribe rxObservable ProducerScope Cold observable that starts coroutine on subscribe rxFlowable ProducerScope Cold observable that starts coroutine on subscribe with backpressure support @askashdavies

Slide 92

Slide 92 text

val service: UserService = retrofit.create() // >= 2.5.0 GlobalScope .rxSingle { service.getUser() } .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( { /* Do something with user */ }, { /* Handle error ... probably */ } ) @askashdavies

Slide 93

Slide 93 text

Completable.await() GlobalScope.launch { Completable .complete() .await() } @askashdavies

Slide 94

Slide 94 text

Maybe.await() GlobalScope.launch { val result: String? = Maybe .fromCallable { null as String? } .await() // result == null } @askashdavies

Slide 95

Slide 95 text

Observable.await... val observable = Observable.just(1, 2, 3, 4) // Await first item val item = observable.awaitFirst() // Print each item observable.consumeEach(::println) // Consume all items observable .openSubscription() .consume { println(it.size) } kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-rx2/kotlinx.coroutines.rx2/io.reactivex.-observable-source/index.html

Slide 96

Slide 96 text

Exceptions @askashdavies

Slide 97

Slide 97 text

! Conclusion @askashdavies

Slide 98

Slide 98 text

Cheers! ! @askashdavies