RACMulticastConnection: NSObject
RACMulticastConnection
用于信号的一对多传播
@property (nonatomic, strong, readonly) RACSignal<ValueType> *signal;
{
RACSubject *_signal;
}
@property (nonatomic, readonly, strong) RACSignal *sourceSignal;
这个signal属性即为对外开发的信号,其实现是使用RACSubject对象,而sourceSignal
即为订阅的原信号
在初始化方法中初始化这两个对象:
- (instancetype)initWithSourceSignal:(RACSignal *)source subject:(RACSubject *)subject {
_sourceSignal = source;
_signal = subject;
}
使用
我们不应该直接初始化RACMulticastConnection
对象 使用RACSignal
的实例化方法初始化这个实例对象:
- (RACMulticastConnection *)publish {
RACSubject *subject = [RACSubject subject];
RACMulticastConnection *connection = [self multicast:subject];
return connection;
}
- (RACMulticastConnection *)multicast:(RACSubject *)subject {
RACMulticastConnection *connection = [[RACMulticastConnection alloc] initWithSourceSignal:self subject:subject];
return connection;
}
可以很简单的看出来这两个方法只是简单的声明了RACSubject
对象,并初始化一个RACMulticastConnection
对象并返回
connect && autoconnect
具体信号的订阅是在connect方法中,只有执行了connect方法 才会订阅该信号 才能接收信号
- (RACDisposable *)connect {
self.serialDisposable.disposable = [self.sourceSignal subscribe:_signal];
}
autoconnect
方法返回一个信号 当订阅了该信号时就会执行connect方法 订阅sourceSignal
从而收到信号值
- (RACSignal *)autoconnect {
return [RACSignal
createSignal:^(id<RACSubscriber> subscriber) {
RACDisposable *subscriptionDisposable = [self.signal subscribe:subscriber];
[self connect];
}];
}]
}
补充
当使用publish
方法返回的RACMulticastConnection
对象时,只有当connect
之前订阅的才能收到消息,而在connect之后订阅的对象并不能收到消息
因此此时我们可以使用RACReplaySubject
对象,可以通过[RACSignal replay]
方法实现
- (RACSignal *)replay {
RACReplaySubject *subject = [RACReplaySubject subject];
RACMulticastConnection *connection = [self multicast:subject];
[connection connect];
return connection.signal;
}
除此之外 还有
Capacity:1 的ReplaySubject
- (RACSignal *)replayLast {
RACReplaySubject *subject = [RACReplaySubject replaySubjectWithCapacity:1];
RACMulticastConnection *connection = [self multicast:subject];
[connection connect];
return connection.signal;
}
只有在返回的信号在被第一次订阅时 才会执行connect方法
- (RACSignal *)replayLazily {
RACMulticastConnection *connection = [self multicast:[RACReplaySubject subject]];
return [RACSignal
defer:^{
[connection connect];
return connection.signal;
}];
}