Willjay
Willjay

Reputation: 6459

How to make synchronous operation with asynchronous callback?

How can I make a synchronous operation with asynchronous function?

class MyClass {
    static let shared = MyClass()
    let operationQueue = OperationQueue()
    let dispatchGroup  = DispatchGroup()

    func request(_ myRequestURL: URL) {
        operationQueue.addOperation {
            self.dispatchGroup.enter()
            // Async function
            Alamofire.request(myRequestURL).response { response in
                print(response.request)
                self.dispatchGroup.leave()
            }

            self.dispatchGroup.wait(timeout: .distantFuture)
        }
    }
}

MyClass.shared.request(A)
MyClass.shared.request(B)
MyClass.shared.request(C)

output: C > A > B
expected: A > B > C


I know there is a completion block method to do so. But the requests will be nested.

func request(_ myRequestURL: URL, completion: @escaping (_ data: Data?) -> Void) {
    // Async function
    Alamofire.request(myRequestURL).response { response in
        completion(response.data)
    }
}

MyClass.shared.request(A) { _ in
     MyClass.shared.request(B) { _ in
         MyClass.shared.request(C) { _ in
        }
    }
}

Upvotes: 11

Views: 8563

Answers (1)

Willjay
Willjay

Reputation: 6459

It works for me using DispatchQueue instead.

class MyClass {
    static let shared = MyClass()
    let dispatchQueue = DispatchQueue(label: "ALAMOFIRE_REQUEST")
    let dispatchGroup  = DispatchGroup()

    func request(_ myRequestURL: URL) {
        dispatchQueue.async {
            self.dispatchGroup.enter()
            // Async function
            Alamofire.request(myRequestURL).response { response in
                print(response.request)
                self.dispatchGroup.leave()
            }

            self.dispatchGroup.wait(timeout: .distantFuture)
        }
    }
}

Upvotes: 22

Related Questions