如何使用调度组同时开始加载?

How can I use dispatch group to start loading at the same time?

为了加快加载速度,我想使用调度组,但在这种情况下该怎么做?

同时我想开始加载 workoutRepository 和 streakRepository。

private func loadDailyWorkout(completion: @escaping ((DailyWorkout) -> Void)) {
    workoutRepository.load { [weak self] (result) in
        switch result {
        case .success(let list):
            if list.isEmpty {
                self?.shouldShowWorkoutUnlockedScreen = true
            }
            self?.streakRepository.load { (result) in
                switch result {
                case .success(let streak):
                    let workout = DailyWorkout(streak: streak, tricks: list)
                    completion(workout)
                case .failure:
                    let workout = DailyWorkout(streak: Streak.initial, tricks: list)
                    completion(workout)
                }
            }
        default:
            completion(DailyWorkout(streak: Streak.initial, tricks: []))
        }
    }
}

这是一个草图:

private func loadDailyWorkout(completion: @escaping ((DailyWorkout) -> Void)) {
    myBackgroundQueue.async {
        let group = DispatchGroup()
        var streak = // Optional of the right type, initially nil
        var list = // Optional of the right type, initially nil
        group.enter()
        workoutRepository.load { result in {
            // do stuff; set list
            group.leave()
        }
        group.enter()
        streakRepository.load { result in
            // do stuff; set streak
            group.leave()
        }
        group.notify(queue: .main) { 
            // can see streak and list
            // so now go ahead and do your callback
        }
    }
}

两个 load 命令同时执行,但我们不会在之后继续 (notify) 直到它们都完成。

请注意,我首先将我们置于后台队列中,因为我们不能在主队列中“等待”。这在您的情况下可能没有必要。