ReativeCocoaRACSignal解读
Posted 王飞飞不会飞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReativeCocoaRACSignal解读相关的知识,希望对你有一定的参考价值。
- 使用
RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
NSLog(@"this is create block");
[subscriber sendNext:@"发送Next"];
return nil;
];
[signal subscribeNext:^(id x)
NSLog(@"this is subscribe block %@",x);
];
- 源码
-
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe return [RACDynamicSignal createSignal:didSubscribe];
继续看RACDynamicSignal createSignal的源码
+ (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe RACDynamicSignal *signal = [[self alloc] init]; signal->_didSubscribe = [didSubscribe copy]; return [signal setNameWithFormat:@"+createSignal:"];
上面源码干了2件事,初始化了RACDynamicSignal类型的信号,把didSubscribe Block 赋值给该信号作为其成员变量。
-
再来看订阅消息的源码
-
- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock NSCParameterAssert(nextBlock != NULL); RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL]; return [self subscribe:o];
新建一个RACSubscriber对象,把nextBlock作为o的一个成员变量。并作为subscribe 方法的参数,继续看subscribe方法的源码。注意这里的RACSignal的类型是RACDynamicSignal。所以要看RACDynamicSignal 的subscribe方法。
-
- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber NSCParameterAssert(subscriber != nil); RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable]; subscriber = [[RACPassthroughSubscriber alloc] initWithSubscriber:subscriber signal:self disposable:disposable]; if (self.didSubscribe != NULL) RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^ RACDisposable *innerDisposable = self.didSubscribe(subscriber); [disposable addDisposable:innerDisposable]; ]; [disposable addDisposable:schedulingDisposable]; return disposable;
这里是比较关键的代码,主要是如果有self.didSubscribe 就去执行,并且执行的参数为subscriber
再继续看看这里的subscriber的初始化方法。
- (instancetype)initWithSubscriber:(id<RACSubscriber>)subscriber signal:(RACSignal *)signal disposable:(RACCompoundDisposable *)disposable
NSCParameterAssert(subscriber != nil);
self = [super init];
if (self == nil) return nil;
_innerSubscriber = subscriber;
_signal = signal;
_disposable = disposable;
[self.innerSubscriber didSubscribeWithDisposable:self.disposable];
return self;
最后再看看sendNext的源码,注意这里didSubscribe block里面的subscribe类型应该是RACPassthroughSubscriber。所以要看 RACPassthroughSubscriber 的sendNext方法。
- (void)sendNext:(id)value
if (self.disposable.disposed) return;
if (RACSIGNAL_NEXT_ENABLED())
RACSIGNAL_NEXT(cleanedSignalDescription(self.signal), cleanedDTraceString(self.innerSubscriber.description), cleanedDTraceString([value description]));
[self.innerSubscriber sendNext:value];
这里其实就是把subscribeNext中传入的block执行了。
- 图解
以上是关于ReativeCocoaRACSignal解读的主要内容,如果未能解决你的问题,请参考以下文章