0
private fun get_rating2(review:String):Float{

    val reviewref = RTDBref.child(review)
    val ratinglist = arrayListOf<Int>()

    var average_rating = 0.0f

    reviewref.get().addOnSuccessListener { reviewsnap ->
        reviewsnap.children.forEach { ratingsnap ->
            val rating = ratingsnap.child("rating").getValue<Int>()
            ratinglist.add(rating!!)
        }
        average_rating = ratinglist.average().toFloat()
        //I need this average_rating Inside of lambda
    }
    return average_rating
    //this average_rating does not return proper value because It is not in lambda
}

How can I return a variable Inside of lambda?

I need to use average_rating Inside of lambda..

2
  • 1
    You need to wait for every value, make the calculation and return it in a callback Commented Oct 31, 2021 at 8:29
  • 1
    See here for explanation: stackoverflow.com/q/57330766/506796 Commented Oct 31, 2021 at 12:51

2 Answers 2

1

If you are using coroutines in your project you just need to use suspend function for your case.

suspend fun getAverageRating(): Float = suspendCancellableCoroutine { continuation -> 
        reviewref.get().addOnSuccessListener { reviewsnap ->
            ...
            continuation.resumeWith(Result.success(ratinglist.average().toFloat()))
        }
        // don't remember unsubscribe you listener on cancellation
}
Sign up to request clarification or add additional context in comments.

Comments

1

that's not lambda scope, it's interface function scope so if you want to do something with average_rating just do it inside the interface function, it's wrong to return the function value get_rating2(review:String) when you need to wait for an interface, for your code it's always 0.0f

So do it like:

private fun get_rating2(review:String){

    val reviewref = RTDBref.child(review)
    val ratinglist = arrayListOf<Int>()

    reviewref.get().addOnSuccessListener { reviewsnap ->
        var average_rating = 0.0f
        reviewsnap.children.forEach { ratingsnap ->
            val rating = ratingsnap.child("rating").getValue<Int>()
            ratinglist.add(rating!!)
        }
        average_rating = ratinglist.average().toFloat()
        doSomthingWith(average_rating)
    }
}

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.