DispatchGroup - Multiple API Calls - Swift Programming

DispatchGroup:

You attach multiple work items to a group and schedule them for asynchronous execution on the same queue or different queues. When all work items finish executing, the group executes its completion handler.
 
You can also wait synchronously for all tasks in the group to finish executing.
 
DispatchGroup instance - Creates a new group to which you can assign block objects.
 

Functions:

enter() - Explicitly indicates that a block has entered the group.

wait() - Waits synchronously for the previously submitted work to finish. Can also used with TimeOut option- DispatchTime - Gives DispatchTimeoutResult

leave() - Explicitly indicates that a block in the group finished executing.

notify() - Schedules the submission of a block with the specified attributes to a queue when all tasks in the current group have finished executing. Can be used with & without QOS


import UIKit

public typealias CompletionHandlerWithBoolStatus = (_ status: Bool) -> Void

// This function handles multiple api request (example posts, comments etc) by executing them simultaneously and once all the api calls got the response will return the status true

func handleMultipleAPICalls(completion: @escaping CompletionHandlerWithBoolStatus) {

    let group = DispatchGroup()
    group.enter() // To track leave status of the first api call - posts
    group.enter() // To track leave status of the first api call - comments
    
    // Call posts API
    API.request(Endpoint.posts).response { response in
        group.leave() // once posts api call got response initiating first group to leave
    }
    
    // Call comments API
    API.request(Endpoint.comments).response { response in
        group.leave() // once comments api call got response initiating second group to leave
    }
    
    group.notify(queue: .main, execute: { // once all the groups perform leave(), notify will be triggered and you can perform the needed actions
        completion(true)
    })
}

Reference Links:

  1. https://gist.github.com/ixcoder001/bacd9352b3eaff4367760ca568ccc243

Comments