DaVincr
DaVincr

Reputation: 115

Cannot convert return expression of type 'Publishers.FlatMap<AnyPublisher<>, AnyPublisher<>>' to return type 'AnyPublisher<>'

I am having difficulties fully understanding Combine. Here I have an issue where I can't seem to return the correct Output type.

How can I do this?

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()
    }
}

Upvotes: 3

Views: 4828

Answers (1)

DaVincr
DaVincr

Reputation: 115

Just like Rob said in his comment, I was missing a .eraseToAnyPublisher() after the flatMap operation.

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
}

Upvotes: 3

Related Questions