坚守本心,拥抱变化
Signal
Subscription
一个Signal就代表一系列正在进行中的事件流,有时候也被叫做热信号,关于冷信号与热信号,请参考夜游er的博文:ReactiveCocoa4中的冷信号和热信号。这就意味着,订阅者可能会丢失订阅之前已发送的事件,而且,订阅信号这个行为不会引起任何的副作用。
分析Subscription例子函数:
scopedExample("Subscription") {
// Signal.pipe is a way to manually control a signal. the returned observer can be used to send values to the signal
let (signal, observer) = Signal<Int, NoError>.pipe()
let subscriber1 = Observer<Int, NoError>(next: { print("Subscriber 1 received \($0)") } )
let subscriber2 = Observer<Int, NoError>(next: { print("Subscriber 2 received \($0)") } )
print("Subscriber 1 subscribes to the signal")
signal.observe(subscriber1)
print("Send value `10` on the signal")
// subscriber1 will receive the value
observer.sendNext(10)
print("Subscriber 2 subscribes to the signal")
// Notice how nothing happens at this moment, i.e. subscriber2 does not receive the previously sent value
signal.observe(subscriber2)
print("Send value `20` on the signal")
// Notice that now, subscriber1 and subscriber2 will receive the value
observer.sendNext(20)
}
看到上面的代码,我的第一反应是为什么该段函数会打印如下内容?
--- Subscription ---
Subscriber 1 subscribes to the signal
Send value `10` on the signal
Subscriber 1 received 10
Subscriber 2 subscribes to the signal
Send value `20` on the signal
Subscriber 1 received 20
Subscriber 2 received 20
cmd+左键点击该函数,跳转到如下的模块文件
怎么仅仅只有一个函数的声明?而且这个ReactiveCocoa_Source是个什么东东?
只看该函数声明,鬼知道这里面写了些啥,于是猜想是不是在头文件中导入了什么别的东西,于是去import部分找:
import Result
import ReactiveCocoa
import Foundation
只有这三个,分析了一遍发现,和他们没有什么关系,于是猜想这个应该是Playground帮我们做了什么事,隐藏了某些东西,于是打开Help -> search里输入playground,我需要的是什么呢?help
打开Playground Help,点击
看完此篇得知:
如果Playground中的每个Page都需要一些辅助的工具代码,将之放在Playground的Source文件夹下是最合适的做法,因为:
- 该文件夹下的辅助工具代码仅仅会被编译一次
- 一旦修改了这些辅助代码,xcode将会自动对其进行编译
- 编译完成的代码会以模块的形式自动导入到每一个page中
那么就可以理解为上面的的ReactiveCocoa_Sources模块是由XCode编译器生成的。
如何验证:
在Source下新建一个Test.swift文件,写下如下内容
注意:这里的函数必须声明为public,这样才能够被外部引用
保存成功后,再次打开ReactiveCocoa_Sources模块发现自动生成了该函数的声明
由此可得,scopedExample函数的实现是在Sources文件夹下的PlaygroundUtility.swift文件中
public func scopedExample(exampleDescription: String, _ action: () -> Void) {
print("\n--- \(exampleDescription) ---\n")
action()
}
而且scopedExample调用时采用的是尾闭包的写法,也就是说如果函数的最后一个参数是一个闭包,而且该闭包的实现比较长的话,是允许将闭包写到函数参数括号外面的,当然不采用尾闭包的写法也是可以的:
scopedExample("Subscription", {
...
})
接下来看函数内部的代码:
let (signal, observer) = Signal<Int, NoError>.pipe()
这里是使用Signal.pipe函数获取signal和对应的observer,值得注意的是指定的泛型Int, NoError,Int是指signal信号指定的event的value类型。
let subscriber1 = Observer<Int, NoError>(next: { print("Subscriber 1 received \($0)") } )
使用Observer结构体的构造函数创建了一个signal的订阅者,传入的参数是一个闭包类型,$0是传入的参数名称的缩写。
signal.observe(subscriber1)
为signal添加订阅者,在此订阅的对象可以接收接下来的signal事件。
observer.sendNext(10)
使用observer发送singal事件,这里的observer对象相当于signal的publisher,对应于前面的subscriber。
最后打印出结果:
...
Send value `10` on the signal
Subscriber 1 received 10
Subscriber 2 subscribes to the signal
Send value `20` on the signal
Subscriber 1 received 20
Subscriber 2 received 20
...
subscriber2是在observer发送完value为10的signal以后才注册订阅的,所以,subscriber2不能收到signal的value为10的事件。
empty
官方的说明是:一个signal将会立即完成,并且不会发送任何值,注意和下面never的区别。
根据打印结果显示,利用Signal.empty构建的signal将会发送一个interrupted事件。
scopedExample("`empty`") {
let emptySignal = Signal<Int, NoError>.empty
let observer = Observer<Int, NoError>(
failed: { _ in print("error not called") },
completed: { print("completed not called") },
interrupted: { print("interrupted called") },
next: { _ in print("next not called") }
)
emptySignal.observe(observer)
}
输出
--- `empty` ---
interrupted called
never
signal不会发送任何事件。
scopedExample("`never`") {
let neverSignal = Signal<Int, NoError>.never
let observer = Observer<Int, NoError>(
failed: { _ in print("error not called") },
completed: { print("completed not called") },
interrupted: { print("interrupted not called") },
next: { _ in print("next not called") }
)
neverSignal.observe(observer)
}
输出
--- `never` ---
Operators
uniqueValues
如果signal的事件value集合中有重复值,那么仅仅会发送一次该事件,uniqueValues将会减少内存消耗。
scopedExample("`uniqueValues`") {
let (signal, observer) = Signal<Int, NoError>.pipe()
let subscriber = Observer<Int, NoError>(next: { print("Subscriber received \($0)") } )
let uniqueSignal = signal.uniqueValues()
uniqueSignal.observe(subscriber)
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendNext(3)
observer.sendNext(3)
observer.sendNext(5)
}
输出
--- `uniqueValues` ---
Subscriber received 1
Subscriber received 2
Subscriber received 3
Subscriber received 4
Subscriber received 5
map
将signal中的每一个值转变为新值。
scopedExample("`map`") {
let (signal, observer) = Signal<Int, NoError>.pipe()
let subscriber = Observer<Int, NoError>(next: { print("Subscriber received \($0)") } )
let mappedSignal = signal.map { $0 * 2 }
mappedSignal.observe(subscriber)
print("Send value `10` on the signal")
observer.sendNext(10)
}
输出
--- `map` ---
Send value `10` on the signal
Subscriber received 20
mapError
将接收到的每一个error转变为新的error。
scopedExample("`mapError`") {
let (signal, observer) = Signal<Int, NSError>.pipe()
let subscriber = Observer<Int, NSError>(failed: { print("Subscriber received error: \($0)") } )
let mappedErrorSignal = signal.mapError { (error:NSError) -> NSError in
let userInfo = [NSLocalizedDescriptionKey: "🔥"]
let code = error.code + 10000
let mappedError = NSError(domain: "com.reactivecocoa.errordomain", code: code, userInfo: userInfo)
return mappedError
}
mappedErrorSignal.observe(subscriber)
print("Send error `NSError(domain: \"com.reactivecocoa.errordomain\", code: 4815, userInfo: nil)` on the signal")
observer.sendFailed(NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil))
}
输出
--- `mapError` ---
Send error `NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)` on the signal
Subscriber received error: Error Domain=com.reactivecocoa.errordomain Code=14815 "🔥" UserInfo={NSLocalizedDescription=🔥}
filter
通过给定的条件来过滤给定signal中的value。
scopedExample("`filter`") {
let (signal, observer) = Signal<Int, NoError>.pipe()
let subscriber = Observer<Int, NoError>(next: { print("Subscriber received \($0)") } )
// subscriber will only receive events with values greater than 12
let filteredSignal = signal.filter { $0 > 12 ? true : false }
filteredSignal.observe(subscriber)
observer.sendNext(10)
observer.sendNext(11)
observer.sendNext(12)
observer.sendNext(13)
observer.sendNext(14)
}
输出
--- `filter` ---
Subscriber received 13
Subscriber received 14
ignoreNil
在返回的signal中如果有nil值,则丢弃。
scopedExample("`ignoreNil`") {
let (signal, observer) = Signal<Int?, NoError>.pipe()
// note that the signal is of type `Int?` and observer is of type `Int`, given we're unwrapping
// non-`nil` values
let subscriber = Observer<Int, NoError>(next: { print("Subscriber received \($0)") } )
let ignoreNilSignal = signal.ignoreNil()
ignoreNilSignal.observe(subscriber)
observer.sendNext(1)
observer.sendNext(nil)
observer.sendNext(3)
}
输出
--- `ignoreNil` ---
Subscriber received 1
Subscriber received 3
take
仅仅返回signal.take(number)函数中的number个数的signal。
scopedExample("`take`") {
let (signal, observer) = Signal<Int, NoError>.pipe()
let subscriber = Observer<Int, NoError>(next: { print("Subscriber received \($0)") } )
let takeSignal = signal.take(2)
takeSignal.observe(subscriber)
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
}
输出
--- `take` ---
Subscriber received 1
Subscriber received 2
collect
当complete事件产生时,观察者将会收到signal的事件组成的数组。当complete事件产生时,没有收到任何的value,则观察者会收到一个空的数组。
scopedExample("`collect`") {
let (signal, observer) = Signal<Int, NoError>.pipe()
// note that the signal is of type `Int` and observer is of type `[Int]` given we're "collecting"
// `Int` values for the lifetime of the signal
let subscriber = Observer<[Int], NoError>(next: { print("Subscriber received \($0)") } )
let collectSignal = signal.collect()
collectSignal.observe(subscriber)
observer.sendNext(1)
observer.sendNext(2)
observer.sendNext(3)
observer.sendNext(4)
observer.sendCompleted()
}
输出
--- `collect` ---
Subscriber received [1, 2, 3, 4]