Combine框架介绍
Combine
框架提供了一个声明式Swift API,用于处理随时间变化的值。这些值可以表示多种异步事件。Combine
声明发布者公开发布可能随时间变化的值,并声明订阅者从发布者接收这些值。
Combine
框架为应用程序如何处理事件提供了一种声明式的方法。可以为给定的事件源创建单个处理链,而不是潜在地实现多个委托回调或完成处理闭包。一个事件及其对应的数据被发布出来,最后被订阅者消化和使用,期间这些事件和数据需要通过一系列操作变形,成为我们最终需要的事件和数据。
Combine中最重要的角色有三种,恰好对应了这三种操作:负责发布事件的Publisher
,负责订阅事件的Subscriber
,以及负责转换事件和数据的Operator
。
Publisher 发布者
Publisher
是一个基础协议,它代表事件的发布者,其他各式各样的Publisher
都继承了这个基础Publisher
协议。Publisher
协议的定义也比较简单,包括两个关联类型(associatedtype
)和一个receive
方法。
public protocol Publisher<Output, Failure> {
/// The kind of values published by this publisher.
associatedtype Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
associatedtype Failure : Error
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
func receive<S>(subscriber: S) where S : Subscriber</