監(jiān)聽器是在等候颈将,或有能力等候來自信號的事件的任何東西焙蚓。監(jiān)聽器用可以接受事件(
Event
)的Observer
類型表示。
監(jiān)聽器可以使用回調(diào)版本的
Signal.observe
或者SignalProducer.start
方法隱性創(chuàng)建寒匙。
其實蝇闭,監(jiān)聽器就是一個函數(shù)(function):Event<Value, Error> -> ()
呻率。在監(jiān)聽器內(nèi)部,這個函數(shù)叫做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?()
}
}
}
......
}
監(jiān)聽器的初始化方法有兩個礼仗,一個很直觀,一個稍微復雜一些逻悠。不過目的都一樣:你決定如何分別處理四種類型的事件元践,初始化方法把這個決定存在監(jiān)聽器里。
2. 如何向監(jiān)聽器發(fā)送事件
取得監(jiān)聽器的引用后童谒,可以用以下四個方法發(fā)送事件:
sendNext(value: Value)
sendFailed(error: Error)
sendComplete()
sendInterrupted()
發(fā)送事件单旁,其實就是將事件的值(發(fā)送Next事件時)或錯誤(發(fā)送Failed事件時)作為參數(shù)調(diào)用監(jiān)聽器的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)
}
}