swift - 无法转换“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()
}
}
解决方案
就像 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
}
推荐阅读
- c - 包含不同值类型的 void 指针的 C 数组
- ansible - Ansible:在树莓派上修改 cmdline.txt
- python - 使用python和管理api将外部数据推送到google analytics 360
- docker - Cannot access tomcat manager or any other default tomcat app when running tomcat in docker
- php - Apache 和虚拟主机返回 NOT FOUND
- javascript - JQuery 不加载 HTML 文件(在 Bootstrap 模板中)
- sql - 检索许多表上的数据 - Laravel
- c - 当文件名在 C 中作为命令行参数传递时,它们是如何存储的?
- docker - docker-compose up OSError 参数无效
- java - Eclipse/RapidClipse X 10.2.2 Java 元素更改通知侦听器发生异常