RACSignal信号的订阅与发送
RACSignal
订阅信号
订阅信号动作 就是创建一个遵循<RACSubscriber>
代理的对象 该对象将接受到信号时要做的动作block保存起来
RACSignal subscribeNext:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock completed:(void (^)(void))completedBlock {
RACSubscriber *subscriber = [[self alloc] init];
subscriber->_next = [next copy];
subscriber->_error = [error copy]
subscriber->_completed = [completed copy];
[self subscribe:subscriber];
}
具体订阅该信号要做的事情 因为不同子类的信号发送事件不同 需要被子类重写
RACSignal subscribe:(id<RACSubscriber>)subscriber {
//被子类重写
}
RACSubscriber
遵循RACSubscriber
代理 即可发送信号值
- (void)sendNext:(id)value {
self.nextBlock(value);
}
- (void)sendError:(NSError *)e{
self.errorBlock(e);
}
- (void)sendCompleted {
self.completedBlock();
}
发送信号值 即执行保存的执行事件block
RACDynamicSignal
DynamicSignal 即在创建信号时要发送的的信号值已经设定 而在重写subscribe
方法时只需要将其发送的值与 next、error、completed block进行匹配执行即可
创建信号
DynamicSignal
创建信号 创建时已经包含了信号已经要发送的值
将id<RACSubscriber>
信号发送者要发送的值的事件block 存起来,存到signal的_didSubscribe
block属性中
RACDynamicSignal createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe {
RACDynamicSignal *signal = [[self alloc] init];
signal->_didSubscribe = [didSubscribe copy];
}
订阅信号
订阅信号 即 执行创建信号时保存起来的didSubscribe
block send创建信号时发送的值
RACDynamicSignal subscribe:(id<RACSubscriber>)subscriber {
self.didSubscribe(subscriber);
}
RASSubject < RACSubscriber >: RACSignal
Subject
维持一个数组保存所有需要sendEvent的Subscriber
,当需要发送
订阅信号
因为继承自RACSignal
需要重写subscribe:
方法
RASSubject )subscribe:(id<RACSubscriber>)subscriber {
[self.subscribers addObject:subscriber];
}
发送信号
发送信号值 即 遍历数组中的Subcriber 依次send 然后执行subscriber 中保存的nextBlock事件block
- (void)sendNext:(id)value {
[self enumerateSubscribersUsingBlock:^(id<RACSubscriber> subscriber) {
[subscriber sendNext:value];
}];
}
RACBehaviorSubject && RACReplaySubject
RACBehaviorSubject
在内部的currentValue
属性会保存上次发送的值 这样在订阅该信号时即能收到最后发送的信号值,进行初始化
+ (instancetype)behaviorSubjectWithDefaultValue:(id)value {
RACBehaviorSubject *subject = [self subject];
subject.currentValue = value;
return subject;
}
发送信号
在发送信号时 保存信号作为最后发送的信号
- (void)sendNext:(id)value {
self.currentValue = value;
[super sendNext:value];
}
订阅信号
重写subscribe
方法 在每次订阅信号时 发送当前保存的值即最后发送的信号
RACBehaviorSubject subscribe:(id<RACSubscriber>)subscriber {
[super subscribe:subscriber];
[subscriber sendNext:self.currentValue];
}
RACReplaySubject
@property (nonatomic, strong, readonly) NSMutableArray *valuesReceived;
内部有个数组保存了一定量发送过的信号 默认为RACReplaySubjectUnlimitedCapacity
(NSUIntegerMax),即保存所有已经发送过的信号,也可以通过initWithCapacity
初始化,制动保存多少个已经发送过的信号
- (instancetype)initWithCapacity:(NSUInteger)capacity {
self = [super init];
_capacity = capacity;
_valuesReceived = (capacity == RACReplaySubjectUnlimitedCapacity ? [NSMutableArray array] : [NSMutableArray arrayWithCapacity:capacity]);
return self;
}