How does Firebase completion callbacks work in Kotlin

前端 未结 1 590
一整个雨季
一整个雨季 2021-01-16 17:03

I have successfully read data from Firebase and displayed it in an imageView asynchronously using a completion callback. Being new to programming,

相关标签:
1条回答
  • 2021-01-16 17:25

    To solve this, you need to create your own callback to wait for Firebase to return you the data. To achieve this, first you need to create an interface like this:

    interface FirebaseCallback {
        fun onCallback(list: MutableList<RecipeTemplate>)
    }
    

    Then you need to create a function that is actually getting the data from the database. This function should look like this:

    fun readFirebaseData(firebaseCallback: FirebaseCallback) {
        ref.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val list = ArrayList<RecipeTemplate>()
                for (ds in dataSnapshot.getChildren()) {
                    val recipeTemplate = ds.getValue(RecipeTemplate::class.java!!)
                    list.add(recipeTemplate)
                }
                firebaseCallback.onCallback(list)
            }
    
            override fun onCancelled(databaseError: DatabaseError) {}
        })
    }
    

    In the end just simply call readData() function and pass an instance of the FirebaseCallback interface as an argument wherever you need it like this:

    readFirebaseData(object : FirebaseCallback {
        override fun onCallback(list: MutableList<RecipeTemplate>) {
            //Do what you need to do with your list
        }
    })
    

    This is the only way in which you can use that value outside onDataChange() function.

    0 讨论(0)
提交回复
热议问题