Kotlin:等待多个Firebase调用在forEach循环中完成

时间:2018-06-13 21:26:45

标签: firebase firebase-realtime-database kotlin

我有以下代码。如果我运行此代码它将工作,但在forEach循环中有两个异步Firebase调用。我想找到最好的方法让它等到通话结束然后再通过下一个。我不知何故需要知道循环已经完成,所以我可以调用完成。提前感谢您的帮助。

fun observeUserChatHistory(complete: Complete) {
    DB_REF.child(ARG_FIREBASE_USERS_TABLE).child(UserRepo.user.id).child(ARG_FIREBASE_USER_MESSAGE_ROOMS).addListenerForSingleValueEvent(object : ValueEventListener {
   override fun onDataChange(dataSnapshot: DataSnapshot) {
            val chatHistoryArray = ArrayList<ChatHistory>()
            val children = dataSnapshot.children
            children.forEach {
                DB_REF.child(ARG_FIREBASE_MESSAGES).child(ARG_MESSAGE_ROOMS).child(it.key!!).limitToLast(1).addListenerForSingleValueEvent(object : ValueEventListener {
                 override fun onDataChange(messageSnapshot: DataSnapshot) {

                        val messageSnap = messageSnapshot.children
                        val messageValue = messageSnap.first().value as HashMap<*, *>
                        val userId = messageValue[ARG_FIREBASE_MESSAGE_TO_ID]
                        val timestamp = messageValue[ARG_FIREBASE_MESSAGE_TIMESTAMP]
                        DataService.getUserData(userId.toString(),{
                            status,data ->
                            if (data is MyUser) {
                                val user = data
                                val lastMessage = messageValue[ARG_FIREBASE_MESSAGE_MESSAGE_TEXT]
                                val chatHistory = ChatHistory(userId.toString(),user.image,user.fullName,lastMessage.toString(),timestamp.toString().toLong())
                                chatHistoryArray.add(chatHistory)
                            }
                        })

                    }

                    override fun onCancelled(p0: DatabaseError) {
                        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                    }

                })

            }

            complete(true)

        }

        override fun onCancelled(p0: DatabaseError) {
            complete(false)
        }

    })
}

0 个答案:

没有答案