Coroutines and RxJava — An Asynchronicity Comparison (Part 6): Threading

Introduction

Slow Rendering

Note that if you’re concerned that you’re doing too much work on the UI thread, there are different ways of profiling your app with Android Studio.

Threading in RxJava

RxJava code to study
subscribeOn defines on which Scheduler the Observable will execute its create method

Note that all RxJava operators that create Observables (i.e. Single.just, Single.zip, etc) internally use Single.create.

The emission of the item will happen on Schedulers.computation()

Note that we use the observeOn operator before applying the transformation and subscribeOn after creating the Observable

Usage of observeOn to execute transformations/observe items in different threads

Note that this is not something that you would do in your app. I’m just swapping to different Schedulers to show how we can do this and how threading works in RxJava.

Transforming the item on Schedulers.io()

Note that a map operator would have also worked here to transform the items. I’m using flatMap to show the power of threading in RxJava.

Transforming the item on Schedulers.computation()
Consuming the item in the Android Main Thread

Threading in Coroutines

Schedulers.computation is a pool of size = CPUs and CommonPool is a pool of size = CPUs — 1

Creating Your Own CoroutineDispatcher

val coroutineDispatcher = newSingleThreadContext("ThreadName")
val coroutineDispatcher = newFixedThreadPoolContext(4, "PoolName")

Threading in Practice

Coroutine code to study

The code in that Coroutine will be executed in background threads.

Using the CoroutineContext of the parent coroutine
The code will be executed in the CommonPool since we use the parent CoroutineContext
Use of newSingleThreadContext
The coroutine will be executed in a new thread we just created to run it
Another way of swapping threads with Coroutines
The code is executed in the context defined as a parameter

withContext vs launch.join

Conclusion

More Education

Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.

Manuel Vivo

Written by

Android DevRel @ Google

Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.