先上个最简单的代码
//1.创建信号(冷信号)
//didSubscribe调用:只要信号被订阅就会调用
//didSubscribe作用:利用subscriber发送数据。
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
//3.发送信号
[subscriber sendNext:@"hello world"];
self.subscriber = subscriber;
return [RACDisposable disposableWithBlock:^{
//只要信号取消订阅就会来这里
NSLog(@"cancel");
}];
}];
//2.订阅信号(热信号)
//nextBlock调用:订阅者发送数据就会调用
//nextBlock作用:处理数据
RACDisposable *disposable = [signal subscribeNext:^(id _Nullable x) {
//x:信号发送的内容
NSLog(@"%@",x);
}];
//默认信号发送完就会取消订阅,只要订阅者在就不会取消订阅。
[disposable dispose];
使用RAC分三步
1.创建信号
2.订阅信号
3.发送信号
每一步具体做了什么,点开源码进行分析。
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe {
return [RACDynamicSignal createSignal:didSubscribe];
}
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe {
RACDynamicSignal *signal = [[self alloc] init];
signal->_didSubscribe = [didSubscribe copy];
return [signal setNameWithFormat:@"+createSignal:"];
}
1.可见在创建信号时返回了RACDynamicSignal
类,该类继承与RACSignal
。在RACDynamicSignal
类里面,初始化了动态信号,保存了传入的didSubscribe
block。在这个block里面,放置的是第三步发送信号的内容。
- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock {
NSCParameterAssert(nextBlock != NULL);
RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL];
return [self subscribe:o];
}
+ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed {
RACSubscriber *subscriber = [[self alloc] init];
subscriber->_next = [next copy];
subscriber->_error = [error copy];
subscriber->_completed = [completed copy];
return subscriber;
}
- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
NSCParameterAssert(subscriber != nil);
RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable];
subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable];
if (self.didSubscribe != NULL) {
RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{
RACDisposable *innerDisposable = self.didSubscribe(subscriber);
[disposable addDisposable:innerDisposable];
}];
[disposable addDisposable:schedulingDisposable];
}
return disposable;
}
2.在订阅信号时,创建了信号订阅者RACSubscriber
,并保存了传入的next
block。 error
和 completed
block默认传入空,暂不分析。然后在subscribe
方法里调用了第一步保存的didSubscribe
block,并将创建的遵守了<RACSubscriber>
协议的RACPassthroughSubscriber
类的对象subscriber
传入该block。此时自动执行第三步发送数据。
- (void)sendNext:(id)value {
@synchronized (self) {
void (^nextBlock)(id) = [self.next copy];
if (nextBlock == nil) return;
nextBlock(value);
}
}
3.由RACSubscriber类发送信号,将在第二步保存的next
block执行。
由此可见,在第一步创建信号时,预先设置了第三步发送信号的内容。在第二步订阅信号时,调用了第一步的block,自动执行第三步发送信号,发送信号是自动调用第二步的block,所以达到了只要订阅了信号,就会自动接收到发送的信号。