RACChannel 可以被理解为一个双向的连接,这个连接的两端都是 RACSignal 实例,它们可以向彼此发送消息,如果我们在视图和模型之间通过 RACChannel 建立这样的连接:
RACChannelTo(self, text) = RACChannelTo(self.ViewModel, text);
那么从模型发出的消息,最后会发送到视图上;反之,用户对视图进行的操作最后也会体现在模型上。这种通信方式的实现是基于信号的, RACChannel 内部封装了两个 RACChannelTerminal 对象,它们都是 RACSignal 的子类.
RACReplaySubject *leadingSubject = [[RACReplaySubject replaySubjectWithCapacity:0] setNameWithFormat:@"leadingSubject"];
RACReplaySubject *followingSubject = [[RACReplaySubject replaySubjectWithCapacity:1] setNameWithFormat:@"followingSubject"];
// Propagate errors and completion to everything.
[[leadingSubject ignoreValues] subscribe:followingSubject];
[[followingSubject ignoreValues] subscribe:leadingSubject];
_leadingTerminal = [[[RACChannelTerminal alloc] initWithValues:leadingSubject otherTerminal:followingSubject] setNameWithFormat:@"leadingTerminal"];
_followingTerminal = [[[RACChannelTerminal alloc] initWithValues:followingSubject otherTerminal:leadingSubject] setNameWithFormat:@"followingTerminal"];
事实上,RACChannel
中一共包含了四个信号,而其中的_leadingTerminal、_followingTerminal
相当于socket,代表了两个端点,主要进行转发将消息及订阅者转发到内部的leadingSubject、followingSubject
,为了方便区分将_leadingTerminal、_followingTerminal
分别称为L终端
,F终端
。
- 实质是就是Channel订阅
leadingSubject
用来接收消息,而发送消息则通过followingSubject
- 由于
RACChannel
通过informal-protocol
实现了自定义的下标访问方法,所以RACChannelTo() = RACChannelTo()
表达式实质上调用了
- (void)setObject:(RACChannelTerminal *)otherTerminal forKeyedSubscript:(NSString *)key {
NSCParameterAssert(otherTerminal != nil);
RACChannelTerminal *selfTerminal = [self objectForKeyedSubscript:key];
[otherTerminal subscribe:selfTerminal];
[[selfTerminal skip:1] subscribe:otherTerminal];
}
其实就是实现了分别订阅对方的followingSubject
- 所以发送消息时通过
followingSubject
发送给了对方的F终端
,而F终端
又会将消息转发给leadingSubject
-
RACChannel实现两个信号,分别用来发送和接收消息,然后通过两个自定义的终端信号将两个信号进行转发,实现双向数据绑定。
Vertical Cross Functional Template.png
网友评论