[转] Combine学习笔记 - Flatmap and error types

参考链接: https://github.com/AvdLee/CombineSwiftPlayground

4天前 7次点击 来自 移动端

标签: 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")!)

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1