Reputation: 2169
The below code give me the desired result,by fetching the data from firestore using coroutine flow.
suspend fun getFeedPer() = flow<State<Any>> {
emit(State.loading())
val snapshot = dbRef.collection("FeedInfo/FeedPercent/DOC/")
.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1)
.get().await()
val post = snapshot.toObjects(FeedPer::class.java)
Log.d("TAG", "getFeedPer: ${snapshot.documents[0].id}")
Log.d("TAG", "getFeedPer: $post")
emit(State.success(post))
}.catch {
emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)
Now i am trying to add one more filter to my query. For that i am using task.
val docRef=dbRef.collection("FeedInfo/FeedPercent/DOC/")
val task1=docRef.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
val task2=docRef.whereLessThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
now how to get it done with coroutine flow.
Please help Thanks
Upvotes: 1
Views: 339
Reputation: 66
You have to put the task in coroutineScope and everything else will be same as before.
emit(State.loading())
var eMsg = ""
val docRef = dbRef.collection("FeedInfo/FeedPercent/DOC/")
val task1 = docRef.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
val task2 = docRef.whereLessThanOrEqualTo("bodyWeight", 0.80)
.orderBy("bodyWeight", Query.Direction.DESCENDING)
.limit(1).get()
/** Need to do query Direction here to get correct data*/
coroutineScope {
val allTask: Task<List<QuerySnapshot>> = Tasks.whenAllSuccess(task1, task2)
allTask.addOnSuccessListener {
for (querySnapshot in it) {
for (documentSnapshot in querySnapshot) {
/** Do your code to get the data */
}
}
}.await()
allTask.addOnFailureListener {
eMsg = it.message.toString()
}
/** Emitting flow based on task status **/
if (allTask.isSuccessful) {
emit(State.success(WhatEverItIs))
} else {
emit(State.failed(eMsg))
}
}
}.catch {
emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)
Upvotes: 5