我试图按照本文的行包装一个tryMap操作符。
extension Publisher where Output == Data {
func decode<T: Decodable>(as type: T.Type = T.self, using decoder: JSONDecoder = .init()) -> Publishers.Decode<Self, T, JSONDecoder> {
decode(type: type, decoder: decoder)
}
}
extension Publisher where Output == URLSession.DataTaskPublisher.Output {
func processData(_: @escaping (Self.Output) throws -> Data) -> Publishers.TryMap<Self, Data> {
tryMap { element -> Data in
guard let httpResponse = element.response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
throw URLError(.badServerResponse)
}
return element.data
}
}
}
当使用它时,我得到一个编译器错误,我正在努力:
return urlSession
.dataTaskPublisher(for: request)
.processData // <- Value of type '(@escaping (URLSession.DataTaskPublisher.Output) throws -> Data) -> Publishers.TryMap<URLSession.DataTaskPublisher, Data>' (aka '(@escaping ((data: Data, response: URLResponse)) throws -> Data) -> Publishers.TryMap<URLSession.DataTaskPublisher, Data>') has no member 'decode'
.decode(as: InstantResponse.self)
.eraseToAnyPublisher()
正确的做法是什么?谢谢!
首先,您没有调用processData
-您错过了括号,这将实际执行函数。第二,你的processData
声明是不正确的,它不应该把闭包作为它的输入参数,因为你无论如何都没有使用那个闭包。
extension Publisher where Output == URLSession.DataTaskPublisher.Output {
func processData() -> Publishers.TryMap<Self, Data> {
tryMap { element -> Data in
guard let httpResponse = element.response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
throw URLError(.badServerResponse)
}
return element.data
}
}
}
return urlSession
.dataTaskPublisher(for: request)
.processData() // parentheses necessary here
.decode(as: InstantResponse.self)
.eraseToAnyPublisher()