上篇已经介绍了RACSignal 冷热信号转换的源码跟踪,本篇主要介绍RACSubject 信号订阅及信号发送的源码跟踪
先贴一段示例代码,待会就对这段代码进行源码跟踪
//1️⃣RACSubject 创建
RACSubject * subject = [RACSubject subject];
//3️⃣ 订阅信号
[subject subscribeNext:^(id x) {
NSLog(@"收到到:%@",x);
}];
//7️⃣ 发送数据
[subject sendNext:@"123"];
贴上我自绘的流程图
这个就是源码的执行步骤,接下来跟着这些步骤,就能弄懂整个源码流程
进入[[RACSubject alloc] init]
- (instancetype)init {
self = [super init];
if (self == nil) return nil;
_disposable = [RACCompoundDisposable compoundDisposable];
//2️⃣ 初始化订阅者列表
_subscribers = [[NSMutableArray alloc] initWithCapacity:1];
return self;
}
进入[subject subscribeNext] -> [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL]
+ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed {
//4️⃣ 初始化订阅者
RACSubscriber *subscriber = [[self alloc] init];
//5️⃣保存next,error,completed(Block)
subscriber->_next = [next copy];
subscriber->_error = [error copy];
subscriber->_completed = [completed copy];
return subscriber;
}
进入[self subscribe:o]
- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
NSCParameterAssert(subscriber != nil);
RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable];
subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable];
NSMutableArray *subscribers = self.subscribers;
@synchronized (subscribers) {
//6️⃣ 将新的订阅者添加到订阅者列表里面
[subscribers addObject:subscriber];
}
[disposable addDisposable:[RACDisposable disposableWithBlock:^{
@synchronized (subscribers) {
// Since newer subscribers are generally shorter-lived, search
// starting from the end of the list.
NSUInteger index = [subscribers indexOfObjectWithOptions:NSEnumerationReverse passingTest:^ BOOL (id<RACSubscriber> obj, NSUInteger index, BOOL *stop) {
return obj == subscriber;
}];
if (index != NSNotFound) [subscribers removeObjectAtIndex:index];
}
}]];
return disposable;
}
进入[subject sendNext]
- (void)sendNext:(id)value {
//8️⃣ 获取所有的订阅者 -- 通过这个block传回所有的订阅者
[self enumerateSubscribersUsingBlock:^(id<RACSubscriber> subscriber) {
//9️⃣ 获取到每个订阅者后执行每个sendNext方法,-->b
[subscriber sendNext:value];
}];
}
- (void)enumerateSubscribersUsingBlock:(void (^)(id<RACSubscriber> subscriber))block {
NSArray *subscribers;
@synchronized (self.subscribers) {
subscribers = [self.subscribers copy];
}
//遍历所有的订阅者,将订阅者返回
for (id<RACSubscriber> subscriber in subscribers) {
block(subscriber);
}
}
进入 [subscriber sendNext:value]
- (void)sendNext:(id)value {
@synchronized (self) {
void (^nextBlock)(id) = [self.next copy];
if (nextBlock == nil) return;
//1️⃣0️⃣ 执行订阅者保存下来的nextblock
nextBlock(value);
}
}
ps:本篇subject sendNext举例,请跟着流程图对源码进行阅读,关键点本人已加上注释。本人能力有限,有什么错误或者表达不清的还望指正。