I've been wondering about whether it is a better approach to use a Handler (Looper.getMainLooper()) or launch a new Coroutine Job to do small things on the Main Thread, like updating a View.
Handler:
val uiHandler = Handler(Looper.getMainLooper())
fun foo() {
uiHandler.post {
someView.update()
}
}
Coroutine
fun foo() {
lifecycleScope.launch {
someView.update()
}
}
I really don't know and couldn't find anything related on the Internet, but I'd love to acquire that knowledge.
You can do both, but I think the common practice is to use coroutines. I don't think handlers are lifecycle aware by default, but coroutines will get cancelled if the view or activity is destroyed. A lot of libraries use suspend functions, so you will have to use coroutines.
Based on this, coroutines add tasks to the event loop just like handlers. I was wondering how coroutines work internally and found this post that uses
mainHandler.post { continuation.resume(value) }to dispatch a coroutine, so I doubt there will be major differences in performance.