0

I'm following along this blog for using Android architecture components with Firebase Realtime Database. Currently, I am at the part where I use a Handler to schedule the removal of a database listener by posting a Runnable callback that performs the removal on a two-second delay after the LiveData becomes inactive.

This is what I have (the Kotlin equivalent of the Java code from the blog):

class FirebaseQueryLiveData(ref: DatabaseReference) : LiveData<DataSnapshot>() {
    private val query: Query = ref
    private val listener: MyValueEventListener = MyValueEventListener()

    private var listenerRemovePending = false

    private val handler: Handler = Handler()

    private val removeListener = object : Runnable {
        override fun run() {
            query.removeEventListener(listener)
            listenerRemovePending = false
        }
    }

    override fun onActive() {
        super.onActive()
        if (listenerRemovePending) {
            handler.removeCallbacks(removeListener)
        } else {
            query.addValueEventListener(listener)
        }
        listenerRemovePending = false
    }

    override fun onInactive() {
        super.onInactive()
        handler.postDelayed(removeListener, 2000)
        query.removeEventListener(listener)
    }

    private inner class MyValueEventListener : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            value = snapshot
        }

        override fun onCancelled(error: DatabaseError) {
            return
        }
    }
}

The problem with this is Handler has been deprecated, so I shouldn't be using this in my code. How do I modify my code to use the suggested alternative of a Handler?

Tom Darious
  • 434
  • 6
  • 18
  • Have you looked into Coroutines? I think you can run this example using a coroutine that runs on the main i.e. `Dispatchers.Main` thread – gtxtreme Sep 06 '21 at 01:57
  • 2
    Handler is not deprecated, but some constructors are deprecated https://stackoverflow.com/questions/61023968/what-do-i-use-now-that-handler-is-deprecated – Zain Sep 06 '21 at 02:10

0 Answers0