[转] Combine学习笔记 - Foundation and Combine

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

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

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

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1