1

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

1
  • Get what done, exactly? What's the desired result, and what are you stuck on with achieving that? Commented Dec 2, 2020 at 15:49

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.