美文网首页源码解析RAC+RxSwift
RACChannelTo() = RACChannelTo()的

RACChannelTo() = RACChannelTo()的

作者: 哦呵呵y | 来源:发表于2018-05-24 16:00 被阅读21次

    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终端

    1. 实质是就是Channel订阅leadingSubject用来接收消息,而发送消息则通过followingSubject
    2. 由于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

    1. 所以发送消息时通过followingSubject发送给了对方的F终端,而F终端又会将消息转发给leadingSubject
    2. RACChannel实现两个信号,分别用来发送和接收消息,然后通过两个自定义的终端信号将两个信号进行转发,实现双向数据绑定。


      Vertical Cross Functional Template.png

    相关文章

      网友评论

        本文标题:RACChannelTo() = RACChannelTo()的

        本文链接:https://www.haomeiwen.com/subject/sassjftx.html