slushy
slushy

Reputation: 12385

Handling async callbacks in a for-in loop with DispatchGroup only works when all loops succeed

The code below is a rough sketch of the task. A database is queried, it returns a collection of results, that collection is looped in search of a specific property, if that property is found, a file storage is immediately queried and its async completion handler returns the file in the loop. Because I am handling async callbacks inside a for-in loop, I use a DispatchGroup to manage that. This setup works only if all of the documents in the collection have the someIdentifier property. If one document in the collection does not have the property, the dispatch group never calls notify() and we are stuck in limbo.

someDatabaseQuery.retrieveSomeData { (data, error) in

    guard let data = data, error == nil else {
        return
    }

    // database has retrieved data, create dispatch group
    let dispatchGroup = DispatchGroup()

    for document in data { // loop through collection

        // check if document has some identifier
        guard let someIdentifier = document["someIdentifier"] as? String else {
            return
        }

        dispatchGroup.enter() // identifier found, enter dispatch

        // perform async operation inside loop
        Filestorage.getSomeFile(forURL: someIdentifier) { (data, error) in

            guard let file = data, error == nil else {
                return
            }

            // download the file
            dispatchGroup.leave() // leave dispatch

        }

    }

    dispatchGroup.notify(queue: .main) {

        // all data grabbed, load table

    }

}

Upvotes: 1

Views: 338

Answers (2)

slushy
slushy

Reputation: 12385

guard let someIdentifier = document["someIdentifier"] as? String else {
    continue // this is the proper control flow statement
}

The problem was simply choosing the wrong control flow statement. When the guard failed inside the loop, return prevented the loop from finishing and never gave dispatch group a chance to notify. The else-clause in the guard should have been continue, which keeps control inside the loop (by letting it finish) and thus gives the dispatch group a chance to notify.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318794

You must call leave if you call enter. But the guard inside the getSomeFile completion block can prevent the call to leave being made even though you called enter.

One solution is to use defer inside the completion block. Call leave inside the defer to ensure it is called no matter how you leave the block.

Upvotes: 3

Related Questions