[转] Combine学习笔记 - Foundation and Combine
参考链接: https://github.com/AvdLee/CombineSwiftPlayground6个月前 • 171次点击 • 来自 移动端
标签: Swift
Foundation and Combine
Foundation adds Combine publishers for many types, like:
- A URLSessionTask publisher and a JSON Decoding operator
- A Publisher for notifications
- KeyPath binding to NSObject instances
- A Timer publisher exposing Cocoa's
Timer
Foundation之与Combine结合使用,包括使用URLSessionTask发起网络请求并解析JSON数据,Notification系统通知等
/*:
### A URLSessionTask publisher and a JSON Decoding operator
*/
struct DecodableExample: Decodable { }
URLSession.shared.dataTaskPublisher(for: URL(string: "https://www.avanderlee.com/feed/")!)
.map { $0.data }
.decode(type: DecodableExample.self, decoder: JSONDecoder())
/*:
### A Publisher for notifications
*/
NotificationCenter.default.publisher(for: .NSSystemClockDidChange)
/*:
### KeyPath binding to NSObject instances
*/
let ageLabel = UILabel()
Just(28)
.map { "Age is \($0)" }
.assign(to: \.text, on: ageLabel)
/*:
### A Timer publisher exposing Cocoa's `Timer`
- this one is a bit special as it is a `Connectable`
- ... use `autoconnect` to automatically start it when a subscriber subscribes
*/
let publisher = Timer
.publish(every: 1.0, on: .main, in: .common)
.autoconnect()