Search code examples
xtend

How to break foreach loop in xtend?


I have below code : Which is iterating the arrayList till end even though I don't want it. I don't know how to break it as xtend does not have break statement. Provided I can't convert the same to a while loop, is there any alternative way in xtend similar to break statement in java?

arrayList.forEach [ listElement | if (statusFlag){
     if(monitor.canceled){
          statusFlag = Status.CANCEL_STATUS
          return
     }
     else{
          //do some stuff with listElement
     }      
}]

Solution

  • You can try something like that

    arrayList.takeWhile[!monitor.cancelled].forEach[ ... do stuff ...]
    if ( monitor.cancelled ) { statusFlag = Status.CANCEL_STATUS }
    

    takeWhile is executed lazily, so it should work as expected and break at correct moment (memory visibility allowing, I hope monitor.cancelled is volatile).

    Not sure how status flag comes into picture here, you might need to add check for it in one or both closures as well.