RAC笔记(1)-- RACMulticastConnectio
2020-04-23 本文已影响0人
喵喵粉
RACMulticastConnection
- (void)mutlticastConnect {
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {//subscriber:RACSubject->RACPassthroughSubscriber
NSLog(@"发送请求");
[subscriber sendNext:@"发送数据"];
return nil;
}];
RACMulticastConnection *connect = [signal publish];
[connect.signal subscribeNext:^(id _Nullable x) {//connect->_signal: <RACSubject
NSLog(@"11:%@", x);
}];
[connect.signal subscribeNext:^(id _Nullable x) {
NSLog(@"22:%@", x);
}];
[connect.signal subscribeNext:^(id _Nullable x) {
NSLog(@"33:%@", x);
}];
[connect connect];//执行signal的block:connect.sourceSignal.didSubscribe(connect.subject)
[connect.signal subscribeNext:^(id _Nullable x) {
NSLog(@"44:%@", x);
}];
[connect connect];
[connect.signal subscribeNext:^(id _Nullable x) {
NSLog(@"55:%@", x);
}];
}
///打印
2020-04-23 18:22:15.932457+0800 RacDemo[1626:631230] 发送请求
2020-04-23 18:22:15.932587+0800 RacDemo[1626:631230] 11:发送数据
2020-04-23 18:22:15.932632+0800 RacDemo[1626:631230] 22:发送数据
2020-04-23 18:22:15.932670+0800 RacDemo[1626:631230] 33:发送数据
- 创建原始信号,保存
block
:didSubscribe
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
}];
image.png
- 创建
RACMulticastConnection
:connect
由RACSignal
对象signal
调用publish
得到
RACMulticastConnection *connect = [signal publish];
publish
方法:
- 将原始信号
signal
赋值给_sourceSignal
:_sourceSignal = source;
- 创建
RACSubject
对象赋值给_signal
:_signal = subject;
- (instancetype)initWithSourceSignal:(RACSignal *)source subject:(RACSubject *)subject {
NSCParameterAssert(source != nil);
NSCParameterAssert(subject != nil);
self = [super init];
_sourceSignal = source;
_serialDisposable = [[RACSerialDisposable alloc] init];
_signal = subject;
return self;
}
-
connect.signal
即connect. subject
调用订阅方法subscribeNext
[connect.signal subscribeNext:^(id _Nullable x) {//connect->_signal: <RACSubject
NSLog(@"11:%@", x);
}];
将订阅者RACSubscriber
封装成RACPassthroughSubscriber
类型,保存到订阅者subscribers
数组
[connect connect]
原始信号signal
订阅subject
将subject
包装成RACPassthroughSubscriber
,做为参数发给原始信号signal
的block
:didSubscribe
执行block
:didSubscribe(RACPassthroughSubscriber)
-
RACPassthroughSubscriber
的sendNext
[subscriber sendNext:@"发送数据"];
RACPassthroughSubscriber.sendNext
RACPassthroughSubscriber.innerSubscriber
是RACSubject
类型,来到RACSubject.sendNext
,遍历保存的订阅者数组subscribers
,发送数据
-
connect
之后的订阅不会执行
OSAtomicCompareAndSwap32Barrier
拿_hasConnected
和 1
比较:
-
_hasConnected
!= 1:返回YES
且_hasConnected = 1
-
_hasConnected
== 1:返回NO
connect
之后的订阅不会执行block
:didSubscribe
,所以后面的44、55
不打印