首页 > 解决方案 > 无法转换“Publishers.FlatMap”类型的返回表达式, AnyPublisher<>>' 返回类型 'AnyPublisher<>'

问题描述

我很难完全理解Combine。在这里,我遇到了一个问题,我似乎无法返回正确的输出类型。

我怎样才能做到这一点?

func test(ticketId: String) -> AnyPublisher<Void, Error> {

    campaignByTicketIdUseCase.execute(ticketId: ticketId)     // this is AnyPublisher<Campaign,Error>
    .flatMap { (campaign) -> AnyPublisher<Void, Error> in     // this is where the error is thrown

        guard let url = URL(string: "url"),
        validator.isParticipationValid(campaignIdentifier: campaign.identifier) else {
            return Result<Void, Error>.failure(HttpError()).publisher.eraseToAnyPublisher()
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        return AuthSession.shared.doRequest(request: request)
        .tryMap({ (_: Data, response: URLResponse) -> Void in
            if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
                throw HttpError()
            }
        }).eraseToAnyPublisher()
    }
}

标签: swiftreactive-programmingcombine

解决方案


就像 Rob 在他的评论中所说的那样,我.eraseToAnyPublisher()在手术后错过了一个flatMap

func test(ticketId: String) -> AnyPublisher<Void, Error> {

    campaignByTicketIdUseCase.execute(ticketId: ticketId)     // this is AnyPublisher<Campaign,Error>
    .flatMap { (campaign) -> AnyPublisher<Void, Error> in     // this is where the error is thrown

        guard let url = URL(string: "url"),
        validator.isParticipationValid(campaignIdentifier: campaign.identifier) else {
            return Result<Void, Error>.failure(HttpError()).publisher.eraseToAnyPublisher()
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        return AuthSession.shared.doRequest(request: request)
        .tryMap({ (_: Data, response: URLResponse) -> Void in
            if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
                throw HttpError()
            }
        }).eraseToAnyPublisher()
    }.eraseToAnyPublisher()       // <-- this was needed to solve the issue
}

推荐阅读