【问题标题】:Cannot convert return expression of type 'Publishers.FlatMap<AnyPublisher<>, AnyPublisher<>>' to return type 'AnyPublisher<>'无法将“Publishers.FlatMap<AnyPublisher<>, AnyPublisher<>>”类型的返回表达式转换为返回类型“AnyPublisher<>”
【发布时间】:2021-10-15 08:31:57
【问题描述】:

我很难完全理解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()
    }
}

【问题讨论】:

  • 如果不出意外,您将返回campaignByTicketIdUseCase.execute(...).flatMap { ... },并且似乎缺少.eraseToAnyPublisher()

标签: swift reactive-programming combine


【解决方案1】:

就像 Rob 在他的评论中所说的那样,在 flatMap 操作之后,我错过了 .eraseToAnyPublisher()

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
}

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多