監聽器是在等候,或有能力等候來自信號的事件的任何東西。監聽器用可以接受事件(
Event
)的Observer
類型表示。
監聽器可以使用回調版本的
Signal.observe
或者SignalProducer.start
方法隱性創建。
其實,監聽器就是一個函數(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. 如何向監聽器發送事件
取得監聽器的引用后,可以用以下四個方法發送事件:
sendNext(value: Value)
sendFailed(error: Error)
sendComplete()
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)
}
}
向監聽器發送事件