Home > Software design >  While loop never return false
While loop never return false

Time:11-09

I have this while loop the problem is if the condition is false it will never break and keeps continue printing as true I'm using firebase to keep tracking of the value

private var gLTF: Boolean? = null

myRef.addValueEventListener(object : ValueEventListener {

    override fun onDataChange(dataSnapshot: DataSnapshot) {
        var gsLvlR = dataSnapshot.child("gLvl").value.toString()
        var gLt = gsLvlR.toInt()

        CoroutineScope(Dispatchers.Default).launch {
            while (checkGsValue(gLt)) {

                println("true")

                if (!checkGsValue(gLt)) {
                    println("false")
                    break
                }
                delay(15000)
            }

        }
    }

    override fun onCancelled(error: DatabaseError) {
        // Failed to read value
    }
})
//Function
fun checkGsValue(gL: Int): Boolean {
    gLTF = gL > 250
    return gLTF as Boolean
}

here the result from the logcat

2021-11-09 04:20:25.888 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:20:40.890 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:20:55.893 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:21:10.894 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:21:25.897 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:21:40.899 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:21:55.901 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:22:10.902 27709-27757/com.example.testing I/System.out: true
2021-11-09 04:22:25.904 27709-27757/com.example.testing I/System.out: true

CodePudding user response:

You are creating an infinite loop for every onDataChange call that isn't gl > 250

This while loop will never end because gLt is not updated in this context it never changes.

        while (checkGsValue(gLt)) {
            println("true")
            if (!checkGsValue(gLt)) {
                println("false")
                break
            }
            delay(15000)
        }

If act upon each snapshot individually when gLvl is 251 it will print false

 override fun onDataChange(dataSnapshot: DataSnapshot) {
        var gsLvlR = dataSnapshot.child("gLvl").value.toString()
        var gLt = gsLvlR.toInt()
        if(checkGsValue(gLt)){
            println("true")
        }else{
            println("false")
        }
 }
  • Related