0

I am trying to update a seekbar every second in background using Kotlin & Coroutines but It says Handler() is deprecated use it with looper and i am confused how to use handler, looper and kotlin coroutines

The code i tried to make it work

val myHandler: Handler = Handler()
myHandler.postAtTime(asyncSeekBar(), 1000)

Here showing Handler() is deprecated

asyncSeekBar()

private fun asyncsSeekBar() {
        CoroutineScope(Default).launch {
            updateSeekBar()
        }
    }

but asyncSeekBar should be Runnable therefore showing and error

Type mismatch. Required: Runnable Found: Unit

If there is any other way of doing it with more simpler way, please suggest

Henry
  • 1,339
  • 13
  • 24
Mohit Kumar
  • 552
  • 9
  • 29
  • Does this answer your question? [What do I use now that Handler() is deprecated?](https://stackoverflow.com/questions/61023968/what-do-i-use-now-that-handler-is-deprecated) – Pouya Heydari Dec 07 '21 at 08:27

2 Answers2

1

You can use LifecycleScope for this to run every second:

lifecycleScope.launch {
    while (true) {
        delay(1000)
        updateSeekBar()
    }
}
Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
1

Why are you using Handler when you have coroutines?

scope.launch {
    delay(1000)  // 1000ms
    asyncSeekBar()
}

The error you're getting is because you're not passing an implementation of Runnable interface, you are instead calling the function and returning the return value which is nothing (Unit) to the postAtTime().

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49