Swift Combine — Publisher、Operator、Subscriber概念介绍

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</
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值