iloveStackOverflow
iloveStackOverflow

Reputation: 49

DispatchGroup Not notifying 'Main" in Swift

I'm trying to use Dispatch group to notify me when a task is finished running. I've written a simple pseudo of what I'm trying to accomplish. For some reason my notify function gets called first.

    class Main {
        let cats = Cats()
        let all = ALL.singleton

        viewdidLoad(){
            cats.makeAllCall
            all.dis()
        }
    }


    class Cats {
    let dispatch = DispatchGroup()
    let all = ALL.singleton

    func makeAllCall(){
        for i in 1...10{
        all.callInfo()
        print("hello")
        }
    }
    }

    class ALL {
    static let singleton = ALL()
    let dispatch = DispatchGroup()

    func dis(){
        dispatch.notify(.main){
            print("working")
        }
    }

    func callInfo(){
        dispatch.enter()
    Alamofire.request("url", headers: headers).responseJSON { response in
            if response.result.isSuccess{
                completion(JSON(response.result.value!))
            }else{
                print("Binance - Couldn't import Request: Please check your internet connection")
            }
        }
        dispatch.leave()
        }
    }

Upvotes: 0

Views: 292

Answers (1)

matt
matt

Reputation: 534966

You have not understood how dispatch groups work. You are calling dis(), apparently in the belief that dispatch.notify is something that you call. It isn't. It is called for you when every enter has been balanced by a leave. A typical structure looks like this pseudo-code:

let group = DispatchGroup()
// here we go...
group.enter()
_queue1_.async {
    // ... do task here ...
    group.leave()
}
group.enter()
_queue2_.async {
    // ... do task here ...
    group.leave()
}
group.enter()
_queue3_.async {
    // ... do task here ...
    group.leave()
}
// ... more as needed ...
group.notify(queue: DispatchQueue.main) {
    // finished!
}

You need to get rid of this bizarre class structure and put everything — the dispatch group, the enter and leave calls, and the notify block — together in one place. If you don't want to do that, then this is not a good use of a dispatch group (perhaps what you wanted was something like Operation and OperationQueue).

Upvotes: 1

Related Questions