Threads vs coroutines
from the CommonsWare Community archivesAt November 4, 2019, 8:23am, Hadysalhab asked:
Hello,
I’m finding it difficult to understand the difference between Java Thread/Runable and Kotlin Coroutine.
How do the two compare to one another?
Android provides multiple framework classes for multi-threading, like AsyncTask, HandlerThread, etc. Do these work with Coroutine somehow or are they completely separate?
Also when building Android apps using Kotlin, when should I be using Coroutine besides when fetching data from Room?
Sorry if this question has an obvious answer or is silly, but I appreciate any clarification you can give me.
Thank you!
Hady
At November 4, 2019, 12:53pm, mmurphy replied:
A coroutine dispatcher (e.g., Dispatchers.Default
) uses threads. Coroutines represent a different way to get work to happen on certain threads or thread pools, one that is more tightly integrated into the Kotlin language and allows us to pretend that all the work is happening on the current thread (from a coding standpoint).
They are completely separate. The ones you cited pre-date Kotlin by several years, let alone pre-date coroutines. Plus, Android’s framework classes are written in Java, not Kotlin.
I cannot tell you when you “should” be using coroutines with Room, as you do not work for me .
Somewhere, you need to do your Room @Dao
calls on a background thread. Your primary options are:
- Set up that thread yourself
- Let Room set up that thread and give you the results by:
LiveData
ListenableFuture
- RxJava types (e.g.,
Observable
,Single
,Completable
) - coroutines (
suspend
functions orFlow
)
Of those options, I prefer coroutines, though they are still young and so there are some stumbling blocks, such as in testing. And I expect that Google will be slowly starting to steer developers towards using coroutines. However, just because I prefer coroutines (and Google does as well) does not mean that everyone does, and you are welcome to use whichever of those options you prefer.