- RACReplaySubject 是 RACSubject的子类
基本使用
#import "ViewController.h"
#import <ReactiveObjC/ReactiveObjC.h>
@interface ViewController ()
@end
@implementation ViewController
// 注意:下面的代码如果 RACSubject 直接创建的对象 是 不能执行成功的
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 1.订阅信号
RACReplaySubject *subject = [RACReplaySubject subject];
// 3.发送信号
[subject sendNext:@"RACReplaySubject的信号"];
// 2.订阅信号
[subject subscribeNext:^(id _Nullable x) {
NSLog(@"第1个订阅信号中的内容是: %@", x);
}];
[subject subscribeNext:^(id _Nullable x) {
NSLog(@"第2个订阅信号中的内容是: %@", x);
}];
[subject subscribeNext:^(id _Nullable x) {
NSLog(@"第3个订阅信号中的内容是: %@", x);
}];
}
@end
执行过程
// RACSubject
// 还是调用类的创建
+ (instancetype)subject {
return [[self alloc] init];
}
// RACReplaySubject
// init 子类重写了
@property (nonatomic, assign, readonly) NSUInteger capacity;
// These properties should only be modified while synchronized on self.
@property (nonatomic, strong, readonly) NSMutableArray *valuesReceived;
- (instancetype)init {
return [self initWithCapacity:RACReplaySubjectUnlimitedCapacity];
}
- (instancetype)initWithCapacity:(NSUInteger)capacity {
self = [super init]; // 调用父类 创建一个订阅者数组
_capacity = capacity;
// 创建一个数组 用于保存 发送的信号值
_valuesReceived = (capacity == RACReplaySubjectUnlimitedCapacity ? [NSMutableArray array] : [NSMutableArray arrayWithCapacity:capacity]);
return self;
}
// 1.创建订阅者和父类是一样的, 保存nextBlock
// 2.真正的订阅信号 进行了重写
- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable];
RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{
@synchronized (self) {
// 如果 self.valuesReceived 有值 就直接发送信号
// 如果没有,就和父类相同, 将信号的值 进行保存
for (id value in self.valuesReceived) {
if (compoundDisposable.disposed) return;
// 发送数组中的每一个值.
[subscriber sendNext:(value == RACTupleNil.tupleNil ? nil : value)];
}
if (compoundDisposable.disposed) return;
if (self.hasCompleted) {
[subscriber sendCompleted];
} else if (self.hasError) {
[subscriber sendError:self.error];
} else {
// 保存数据
RACDisposable *subscriptionDisposable = [super subscribe:subscriber];
[compoundDisposable addDisposable:subscriptionDisposable];
}
}
}];
[compoundDisposable addDisposable:schedulingDisposable];
return compoundDisposable;
}
- (void)sendNext:(id)value {
@synchronized (self) {
// 如果已经添加过, 则value有值,不再需要进行添加
// 如果没有添加,则添加RACTupleNil单例对象,保存到valuesReceived数组中去.
[self.valuesReceived addObject:value ?: RACTupleNil.tupleNil];
// 调用父类进行遍历所有的订阅者进行发送数据 执行nextBlock
[super sendNext:value];
// 清空已发送数据
if (self.capacity != RACReplaySubjectUnlimitedCapacity && self.valuesReceived.count > self.capacity) {
[self.valuesReceived removeObjectsInRange:NSMakeRange(0, self.valuesReceived.count - self.capacity)];
}
}
}