Home > Blockchain >  How can I return a variable inside of lambda
How can I return a variable inside of lambda

Time:10-31

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..

CodePudding user response:

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)
    }
}

CodePudding user response:

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
}
  • Related