ReactiveCocoa 4 图解之二——监听器(Observer)

监听器是在等候,或有能力等候来自信号的事件的任何东西。监听器用可以接受事件(Event)的Observer类型表示。

监听器可以使用回调版本的Signal.observe或者SignalProducer.start方法隐性创建。

—— ReactiveCocoa 框架概览

其实,监听器就是一个函数(function):Event<Value, Error> -> ()。在监听器内部,这个函数叫做action。它接收一个事件对之进行处理:

public struct Observer<Value, Error: ErrorType> {
    public typealias Action = Event<Value, Error> -> ()

    public let action: Action

    public init(_ action: Action) {
        self.action = action
    }

    public init(failed: (Error -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (Value -> ())? = nil) {
        self.init { event in
            switch event {
            case let .Next(value):
                next?(value)

            case let .Failed(error):
                failed?(error)

            case .Completed:
                completed?()

            case .Interrupted:
                interrupted?()
            }
        }
    }

    ......
}

监听器的初始化方法有两个,一个很直观,一个稍微复杂一些。不过目的都一样:你决定如何分别处理四种类型的事件,初始化方法把这个决定存在监听器里。

监听器的构成

2. 如何向监听器发送事件



取得监听器的引用后,可以用以下四个方法发送事件:

  1. sendNext(value: Value)
  2. sendFailed(error: Error)
  3. sendComplete()
  4. sendInterrupted()

发送事件,其实就是将事件的值(发送Next事件时)或错误(发送Failed事件时)作为参数调用监听器的action

public struct Observer<Value, Error: ErrorType> {
    
    ......

    /// Puts a `Next` event into the given observer.
    public func sendNext(value: Value) {
        action(.Next(value))
    }

    /// Puts an `Failed` event into the given observer.
    public func sendFailed(error: Error) {
        action(.Failed(error))
    }

    /// Puts a `Completed` event into the given observer.
    public func sendCompleted() {
        action(.Completed)
    }

    /// Puts a `Interrupted` event into the given observer.
    public func sendInterrupted() {
        action(.Interrupted)
    }
}
向监听器发送事件
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 6,424评论 0 6
  • 一个信号,由Signal类型表现,是可以被持续监视的一系列事件(events)。 信号一般用来表示“正在进行中”的...
    HetfieldJoe阅读 4,757评论 16 21
  • ❀平生不会相思,才会相思,便害相思。 ❀生下来本是不会相思的,所以日后便会相思,故而便害了相思。一开始的相思来得热...
    泛泛之檀阅读 341评论 0 1
  • ListView的优化问题可以说是面试的必考题。我之前看过一遍视频 Android必学-异步加载,感觉里面讲解的知...
    mecury阅读 13,153评论 9 64