Swift Combine 基本學習與使用
Combine基本認知
Combine 是基于泛型實現的,是類型安全的。它可以無縫地接入已有的工程,用來處理現有的 Target/Action、Notification、KVO、callback/closure 以及各種異步網絡請求。
Combine 是基于觀察者模式,響應式編程的編程思想
觀察者模式: 一種設計模式,用來描述一對多關系:一個對象發生改變時將自動通知其他對象,其他對象將相應做出反應。
觀察者設計模式特點:觀察者之間彼此時互相獨立的,也并不知道對方的存在。
響應式編程(Reactive Programming)是一種編程思想
響應式編程的核心:是面向異步數據流和變化的
在實際開發的過程中,面對紛繁復雜的用戶交互,觸發事件,網絡交互,系統通知,響應式編程幫助我們把事件處理成為異步的數據流,我們只需要監聽所關心的數據流的變化,按需做出相應即可
在 Combine 中,有幾個重要的組成部分:
- 發布者:Publiser : 觀察者模式中被監聽的對象
- 訂閱者:Subscriber :監聽者
- 操作符:Operator: publiser通過各種各樣的操作符把不相關的邏輯編程一致的(unified)、聲明式的(declarative)的數據流
舉例使用
一 @Published
@Published var foo:String = "test" //@Published是Combine的修飾屬性,標識這是個被觀察的對象 即發布者
let subscription = $foo.sink { print("foo is \($0)") }//發布者通過 sink 訂閱 Publisher 事件
foo = "\(indexPath.row)" //發布者對象發生變化時候 Subscriber 監聽到就會執行 sink
//?? 如果發現只執行了一次監聽 或者 無法監聽 是因為Subscriber 訂閱者訂閱的數據流的作用域問題,可考慮把發布者或者訂閱者設計為實例變量持有即可
二 PassthroughSubject
PassthroughSubject 發布者:狀態管理外部數據監聽 //創建一個實際的傳遞主題實例 默認初始化器 let passThroughSubject = PassthroughSubject<String, Error>() //先訂閱 let subscription = passThroughSubject.sink( receiveCompletion: { completion in print("Received completion (sink)", completion) }, receiveValue: { value in print("Received value (sink)", value) }).store(in: &cancellables) //??如果沒有store 方法 只執行一次,需要把訂閱者存住The set in which to store this ``AnyCancellable``. //后接收
passThroughSubject.send("Hello1 ") passThroughSubject.send("Hello2”)
三 異步參考Future
let downloadPublisher = Future<Data?, Error> { promise in URLSession.shared.dataTask(with: URL.init(string: "https:www.1")!) { ( data, response, error) in if (data != nil) && error == nil { promise(.success(data)) } else { promise(.failure(error!)) } }.resume() } let cancellable = downloadPublisher.sink { (result) in switch result { case .failure(let error): Log(error.localizedDescription) default: break } } receiveValue: { value in print("Received value (sink)", value) }.store(in: &cancellables)
//需要取消監聽
cancellable.cancel()
參考
1 https://www.jianshu.com/p/df8535b40079
2 https://icodesign.me/posts/swift-combine/
3 https://blog.csdn.net/iCloudEnd/article/details/106252106
posted on 2021-03-24 11:50 ACM_Someone like you 閱讀(1312) 評論(0) 收藏 舉報
浙公網安備 33010602011771號