'How can I start and stop a for loop with the press of a button in Android Studio?

I have made a button on clicking which goes through a list and takes out individual items and sends them via Bluetooth to the hardware.
What I want to do is when I click the button once again it should stop the execution of the loop in between and no more values should be sent.
I have tried making it with a variable, which turns true and false on the clicking and the loop continues only when the variable is true.

Here it is:

run.setOnClickListener{
        if (!stop){
            stop = true
            runList()
        }
        else{
            stop = false
        }
    }

 private fun runList() {
    for (i in 0 until order.size) {
        if(stop) {
            //Elements to send come here, using order[i] 
        }
        if (!stop) {
            break
        }
    }
}

But in this code, the loop just continues till the very end when all the items are completed even if I click the button again in between the execution. Could someone please help me out?



Solution 1:[1]

I think that your logic is confused. Try with this.

 run.setOnClickListener{
    if (!stop){
        stop = true
    }else{
        stop = false
    }
    runList();
}

 private fun runList() {
 if(stop){
     for (i in 0 until order.size) {
      //Elements to send come here, using order[i] 
     }
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1