美文网首页
Combine进化之路2——Publisher

Combine进化之路2——Publisher

作者: valiant_xin | 来源:发表于2023-09-07 11:44 被阅读0次

    发布者 Publisher

    在Combine中,Publisher是观察者模式中的Observable,并且可以通过组合变换(利用Operator)重新生成新的Publisher。

    /// # Creating Your Own Publishers
    ///
    /// Rather than implementing the `Publisher` protocol yourself, you can create your own publisher by using one of several types provided by the Combine framework:
    ///
    /// - Use a concrete subclass of ``Subject``, such as ``PassthroughSubject``, to publish values on-demand by calling its ``Subject/send(_:)`` method.
    /// - Use a ``CurrentValueSubject`` to publish whenever you update the subject’s underlying value.
    /// - Add the `@Published` annotation to a property of one of your own types. In doing so, the property gains a publisher that emits an event whenever the property’s value changes. See the ``Published`` type for an example of this approach.
    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
    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, Self.Failure == S.Failure, Self.Output == S.Input
    }
    

    在Publisher定义中,Output代表数据流中的输出值,值的更新可能是同步或者异步。Failure代表可能产生的错误。Publisher最核心的是定义了值与可能的错误
    Publisher通过receive(subscriber:)接受订阅,并且要求Subscriber的值和错误的类型一致来保证类型安全。
    官方例子:

    extension NotificationCenter {
            struct Publisher: Combine.Publisher {
                    typealias Output = Notification
                    typealias Failure = Never
                    init(center: NotificationCenter, name: Notification.Name, object: Any? = nil)
            }
    }
    

    例子中,Publisher提供的值是Notification类型,而且永远不会产生错误(Never)。这个扩展很方便的将任何Notification转换成Publisher,便于我们将应用改造成Reactive。

    Just

    只发送一次消息就结束

    let justPublisher = Just("一次消息")
    

    Empty

    不提供任何值更新,并且可以选择立即正常结束。

    func emptyFunc() {
            // 只发送一次消息,不带任何信息
            let emptyPublisher = Empty(completeImmediately: true, outputType: (Any).self, failureType: Never.self)
            let emptyPublisher2 = Empty<Any, Never>(completeImmediately: false)
        }
    

    Once

    Once可以提供两种数据流之一:

    1. 发送一次值更新,然后立即正常结束(和Just一样)
    2. 立即因错误而终止
    没有找到对应的API,还在翻阅资料中……
    

    Fail

    1. 发送一次值更新,然后立即因错误而终止
    2. 立即因错误而终止
    
    enum NetWorkError: Error, Equatable {
        case message(String, Any?)
        case noNetWork
        
        static func == (lhs: NetWorkError, rhs: NetWorkError) -> Bool {
            lhs.errorDescription == rhs.errorDescription
        }
    }
    extension NetWorkError: LocalizedError {
        var errorDescription: String? {
            return "\(self)"
        }
    }
    
    
    let failPublisher = Fail(outputType: Any.self, failure: NetWorkError.message("我是错误", nil))
    

    Sequence

    将给定的一个序列按序通知到订阅者。

    let sequencePublisher = [1, 2, 3].publisher
    

    Future

    Future需要提供执行具体操作的closure,这个操作可以是异步,最终返回一个Result。
    所以Future要么发送一个值正常结束,要么因错误而终止。在将一些一步操作转换为Publisher时非常有用,特别是网络请求。

    let future = Future<Data?, Never> { promise in
                URLSession.shared.dataTask(with: URL(string: "https://api")!) { data, response, error in
                    promise(.success(data))
                }.resume()
            }
    

    Deferred

    deferred初始化需要提供一个closure,只有在Subscriber订阅的时候才会生成指定的Publisher,并且每个Subscriber获取到的Publisher都是全新的

    let deferredPublisher = Deferred {
                return Just(arc4random())
    }
    

    延时发布消息

    可以使用delay方法,生成一个新的Publisher。

    // 只发送一次消息
    let justPublisher = Just("一次消息")
            
    // 延迟2秒发布消息
    let delyPublisher = justPublisher.delay(for: 2, scheduler: DispatchQueue.main)
    

    Combine进化之路合集

    相关文章

      网友评论

          本文标题:Combine进化之路2——Publisher

          本文链接:https://www.haomeiwen.com/subject/kfolvdtx.html