[转] Combine学习笔记 - Flatmap and error types
参考链接: https://github.com/AvdLee/CombineSwiftPlayground6个月前 • 169次点击 • 来自 移动端
标签: Swift
flatmap
- with
flatmap
you provide a new publisher every time you get a value from the upstream publisher - ... values all get flattened into a single stream of values
- ... it looks like Swift's
flatMap
where you flatten inner arrays of an array, just asynchronous.
matching error types
- use
mapError
to map a failure into a different error type
示例使用网络请求演示了如何使用flatmap
把上游输出的值转换为一个新的pulisher与错误处理
//: define the error type we need
enum RequestError: Error {
case sessionError(error: Error)
}
//: we will send URLs through this publisher to trigger requests
let URLPublisher = PassthroughSubject<URL, RequestError>()
//: use `flatMap` to turn a URL into a requested data publisher
let subscription = URLPublisher.flatMap { requestURL in
URLSession.shared
.dataTaskPublisher(for: requestURL)
.mapError { error -> RequestError in
RequestError.sessionError(error: error)
}
}
.assertNoFailure()
.sink { result in
print("Request completed!")
_ = UIImage(data: result.data)
}
URLPublisher.send(URL(string: "https://httpbin.org/image/jpeg")!)