1

Simplified version of my code is like this:

var joined = false

for room in rooms {
    checkRoom() { // async func
        if room.player.count == 1 { 
            join(room)
            joined = true
            // break doesnt work here
        }
    }

    if joined {
        break;
    }
}

I need to exit this loop because it is still checking other rooms after joining one. I want to stop checking rest of rooms when joined becomes true. But ofcourse it becomes true in async call only so my method does not work.

How can I exit this loop when joined becomes true?

2
  • 3
    The first thing, is do you want to check rooms in parallel or serially. If you can do it serially then it is pretty simple; don't use a for loop, simply check the next room in the else statement in your closure Commented Oct 28, 2018 at 6:40
  • @Paulw11 Oh... It seems I made it harder than it should be by using for loop. Thank you! Commented Oct 28, 2018 at 9:35

1 Answer 1

1

async function call should be avoided inside loop. Suppose checkRoom() method makes API call internally. In that case, loop will run for all rooms and API requests for all rooms would be queued regardless of when you get response for each request.

Ideally you should replace loop with recursion. Call checkRoom() inside a function, let's call it mainFunction(), and wait for the response. If your criterion for joining room doesn't meet, then call your mainFunction() recursively which will make next call to checkRoom() function. Something like this:

var rooms: Array<Room> = []
var currentRoomIndex: Int = 0

func mainFunction() {

        checkRoom() { // async func
            let room = rooms[currentRoomIndex]
            if room.player.count == 1 {
                join(room)
                joined = true
                break
            } else {
                currentRoomIndex += 1
                mainFunction()
            }
        }
}

Another way would be to add all your calls to checkRoom() function (probably API requests) to a queue and as soon as your room joining criterion meets, stop tasks/requests that are still pending in the queue.

Sign up to request clarification or add additional context in comments.

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.