RxSwift flatMap如何等待for循环完成?

问题描述 投票:0回答:1

在我的代码中有一个Single,而我flapMap它发出一个array。在flapMap中有一个for loop,每次都会向数组添加一个元素。我的问题是:flapMap return调用如何等待for循环完成?代码是这样的:

 SomeSingle
  .flatMap { firstMapReturned -> Single<Result<[ExpandableComment], Error>> in
        switch firstMapReturned {
            case .success(let returnedArray):
                var expandableCommentsArray: [ExpandableComment] = []

                for item in returnedArray {
                    let replies = item.comment.children

                    var replyUserRequests: [Single<Result<User, Error>>] = []
                    var replyRequestAndIndex: [String:Int] = [:]

                    for i in 0..<replies.count {
                        let replyUserRequest = AppEnv.current.user.getUser(userId: replies[i].userId)
                        replyUserRequests.append(replyUserRequest)
                        replyRequestAndIndex[replies[i].userId] = i
                    }

                    return Single.zip(replyUserRequests)
                        .map ({ a -> Result<[ExpandableComment], Error> in
                            let replyItems: [CommentItem] = a.compactMap { result in
                                guard case .success(let replyUser) = result else { return nil }
                                guard let n = replyRequestAndIndex[replyUser.id] else { return nil }

                                return CommentItem(profileImageUrl: replyUser.profileImageUrl, username: replyUser.username, contents: item.comment.children[n].contents, timestamp: item.comment.children[n].createdAt, replies: [])
                            }
                            let commentItem = CommentItem(profileImageUrl: item.commentUser.profileImageUrl, username: item.commentUser.username, contents: item.comment.contents, timestamp: item.comment.createdAt, replies: replyItems)
                            let expandableItem = ExpandableComment(isExpanded: false, commentItem: commentItem, commentId: item.comment.id)

                            expandableCommentsArray.append(expandableItem)

                            return .success(expandableCommentsArray)
                        })

                }
                //How to wait until the above for loop finishes to get the complete expandableCommentsArray?

                return .just(.success(expandableCommentsArray))
            case .failure(let e):
                return .just(.failure(e))
        }
    }
asynchronous rx-swift flatmap
1个回答
0
投票

您的问题是您的for循环中有一个return,因此循环永远不会结束。您将必须删除该退货。

© www.soinside.com 2019 - 2024. All rights reserved.