系列文章
RACSignal,RACSubject,RACReplaySubject
RAC bind
RAC Merge flatten
RACMulticastConnection
RAC switchToLatest
多次订阅信号,则会多次调用创建信号时的block,如果想要多次订阅,只会调用一次,就需要用到RACMulticastConnection
类。
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
NSLog(@"订阅");
[subscriber sendNext:@"a"];
return nil;
}];
RACMulticastConnection *connect = [signal publish];
[connect.signal subscribeNext:^(id x) {
NSLog(@"1 - %@",x);
}];
[connect.signal subscribeNext:^(id x) {
NSLog(@"2 - %@",x);
}];
[connect.signal subscribeNext:^(id x) {
NSLog(@"3 - %@",x);
}];
[connect connect];
...
// connect 内部实现
- (RACDisposable *)connect {
BOOL shouldConnect = OSAtomicCompareAndSwap32Barrier(0, 1, &_hasConnected);
if (shouldConnect) {
self.serialDisposable.disposable = [self.sourceSignal subscribe:_signal];
}
return self.serialDisposable;
}
RACMulticastConnection
实现步骤
-
[signal publish]
会生成一个RACMulticastConnection
对象, connect内部会生成一个RACSubject
对象保存为signal
,将原signal
保存为sourceSignal
- 后面对
connect.signal
进行订阅,其实是对connect内部的RACSubject
对象进行订阅。 - 当调用
[connect connect];
时,通过[self.sourceSignal subscribe:_signal]
方法将RACSubject
对象作为原信号的订阅者,这是原信号创建时的block才会调用,通过OSAtomicCompareAndSwap32Barrier(0, 1, &_hasConnected)
也保证了,此方法只会执行一次 - 此时原信号创建时的block内部传入的订阅者就是
connect.signal(RACSubject)
,然后订阅者发送信号,所有订阅者都会收到消息。
网友评论