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

原文地址:https://www.cnblogs.com/someonelikeyou/p/14572921.html