6

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.

user3738870
  • 1,415
  • 2
  • 12
  • 24
Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61
  • why are you _not_ on the main thread ? what are you doing ? perhaps that's relevant to people giving answers – a_local_nobody Feb 22 '21 at 13:59
  • Gotcha! There are some situations where you can find yourself having to do somethings in a background thread and in the Main Thread in the same method. Or where it is impossible to know in which thread you are in. – Augusto Carmo Feb 22 '21 at 14:01
  • i understand what you're saying and when thread switching is needed, but i wanted to know what _you_ are doing specifically :) are you doing background coroutine operations and then need to do something on the main thread when you're done, or why would _you_ be on the background thread – a_local_nobody Feb 22 '21 at 14:03
  • Actually my question is for common knowledge - having performance and memory as the main focus. We've gotta consider that `foo()` is not called from a coroutine. – Augusto Carmo Feb 22 '21 at 14:05
  • 1
    Did you ever find the right solution? I am wondering the same. – IgorGanapolsky Aug 10 '22 at 17:35

2 Answers2

0

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.

BPDev
  • 397
  • 1
  • 9
0

well they both do the same thing. but if we want to choose we should consider these facts :

  • in performing UI update on main thread, coroutine is recommended. because it has better consistency when coding with coroutines.

  • if you want more control in timing stuff like delaying and posting at desired time, Handler is a better option.

  • finally in today's android development, using coroutines and handling stuff with it is recommended.

Sep
  • 147
  • 8