Swift5.0 - 学习笔记 DispatchGroup

起源

  • 有一个界面的数据需要涉及多个网络请求,然后等所有网络请求完成后统一处理数据

代码

 // MARK: 网络请求调度组
    func datesRequestGroup(_ pickpickId: String){
        let group = DispatchGroup()
        let groupQueue = DispatchQueue(label: "hot_comment_requst")
        
        // 网络请求A
        group.enter()
        groupQueue.async {
            CommentService.init().hotCommentInfo(withPickPickId: pickpickId) { (responseData, code, responseString) in
                guard code == 200 else {
                    group.leave()
                    return
                }
                self.hotCommentBaseData = CommentBaseData.model(with: responseData)
                guard let list = self.hotCommentBaseData?.data else {
                    group.leave()
                    return
                }
                self.hotcomments.removeAll()
                self.hotcomments = self.commentDataHandle(list, isHotComment: true)
                group.leave()
            }
        }
        
        // 网络请求B
        group.enter()
        groupQueue.async {
            UserService.init().queryPickItemCommentList(withPickId: pickpickId, scroll: "") { (responseObject, code, responseString) in
                guard code == 200 else {
                    group.leave()
                    return
                }
                
                self.commentsBaseData = CommentBaseData.model(with: responseObject)
                guard let list = self.commentsBaseData?.data else {
                    group.leave()
                    return
                }
                self.comments.removeAll()
                self.comments = self.commentDataHandle(list)
            }
        }
        
        // 调度组里的任务都执行完毕执行
        group.notify(queue: groupQueue) {
            self.totalList.removeAll()
            self.totalList = self.hotcomments + self.comments
        }
    }

注意

  • group.enter()group.leave()必须成对出现

你可能感兴趣的:(Swift5.0 - 学习笔记 DispatchGroup)