Subscribing to a Signal
对于一个“普通”的信号,每次订阅都将会导致信号中的代码再执行一遍,且该次订阅者仅接收到该次订阅发送出去的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
__block
int
num = 0;
RACSignal *
signal
= [RACSignal createSignal:^RACDisposable *(id subscriber) {
num++;
NSLog(@
"Increment num to: %i"
,num);
[subscriber sendNext:@(num)];
return
nil;
}];
"Start subscriptions"
);
// Subscriber 1 (S1)
[
subscribeNext:^(id x) {
"S1: %@"
// Subscriber 2 (S2)
subscribeNext:^(id x) {
"S2: %@"
// Subscriber 3 (S3)
subscribeNext:^(id x) {
"S3: %@"
|
运行结果如下:
Start subscriptions
Increment num to: 1
S1: 1
Increment num to: 2
S2: 2
Increment num to: 3
S3: 3
|
可以看到,每次订阅num都在递增,如果不订阅则不会递增。通过这种方式,可以知道信号是懒惰的,如果没有订阅者的话,是不会执行的。
第二个例子演示信号被添加订阅的时候,订阅者是怎么接收发送的值的。
RACSubject *letters = [RACSubject subject];
= letters;
"Subscribe S1"
);
subscribeNext:^(id x) {
"Send A"
[letters sendNext:@
"A"
];
"Send B"
);
"B"
];
"Subscribe S2"
);
subscribeNext:^(id x) {
"Send C"
);
"C"
];
"Send D"
);
"D"
];
"Subscribe S3"
);
subscribeNext:^(id x) {
|