(Android, Kotlin)
I'm trying to recover data from firebase through a repository and It is happening correctly but in the wrong time
override suspend fun getAllOnline(): MutableStateFlow<ResourceState<List<DocModel>>> {
val docList: MutableList<DocModel> = mutableListOf()
auth = FirebaseAuth.getInstance()
database
.child(auth.currentUser!!.uid)
.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for(docs in snapshot.children) {
val doc = docs.getValue(DocModel::class.java)
docList.add(doc!!)
}
}
override fun onCancelled(error: DatabaseError) {
return
}
})
return if(docList.isNullOrEmpty()) {
MutableStateFlow(ResourceState.Empty())
} else {
MutableStateFlow(ResourceState.Success(docList))
}
}
The problem is: my doc list is populated after the return finishes. I've debugged and logged it and the result always come after the function is ended, so it return no data.
It is necessary to somehow only allow the return when the data retrieve is completed.
Any suggestions?
Thanks in advance