Wait for closure completion to make a synchronous function return

Viewed 43

I have a function that returns a Bool. This Bool value is set inside a closure that is executed after get network response(network request is performed in a background thread).

The problem is that I need to wait for closure completion ir order to obtain the value that I need to return.

In order to achieve this I have used DispatchGroup but it does not work. As result my application is get blocked by some kind of deadlock.

private func isOriginal() -> Bool {
        let group = DispatchGroup()
        var isOriginal = true
        group.enter()
        let parameters = GetIsOriginalParameters(completion: { result in
            defer {
                group.leave()
            }
            guard case .success(let isOriginalResult) = result else {
                return
            }
            isOriginal = isOriginalResult
        })
        getIsOriginalUseCase.run(parameters) //calls network request 
        group.wait()
        return isOriginal
    }

Notice that I have test with DispatchSemaphore obtaining same behaviour. I can't support Async/Await

Edit: This code is part of an enum initiated from AppDelegate after open a push notification:

public var navigationInfo: NavInfo {
        switch self {
        .
        .
        case .createNew:
            return handleTypeNavigation()
        .
        .
        }
    }

    private func handleTypeNavigation() -> NavInfo {
        if isOriginal() {
            return Navigation.original
        } else {
            return Navigation.notOriginal
        }
    }
0 Answers
Related