RACSubscriber协议和类、RACPassthrough

2019-04-03  本文已影响0人  boy丿log

RACSubscriber

RACSubscriber协议

这个协议定义给RACSignal发送消息的是三个基本方法:

//发送数据
- (void)sendNext:(nullable id)value;

//发送失败消息
- (void)sendError:(nullable NSError *)error;
//发送完成消息
- (void)sendCompleted;
//从方法调用来看应该是添加销毁任务的
- (void)didSubscribeWithDisposable:(RACCompoundDisposable *)disposable;

RACSubscriber类

这个类的头文件是#import "RACSubscriber+Private.h"

只暴露了一个初始化方法:

+ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed{
RACSubscriber *subscriber = [[self alloc] init];

    subscriber->_next = [next copy];
    subscriber->_error = [error copy];
    subscriber->_completed = [completed copy];
}

这个方法在初始化时设置三个block,next,error,completed和disposable,这个销毁任务在dispose的时候把RACSubscriber对象的三个属性都置nil,如下:

RACDisposable *selfDisposable = [RACDisposable disposableWithBlock:^{
        @strongify(self);

        @synchronized (self) {
            self.next = nil;
            self.error = nil;
            self.completed = nil;
        }
}];

RACSubscriber对象实现了三个代理方法:

- (void)sendNext:(id)value {
    @synchronized (self) {
        void (^nextBlock)(id) = [self.next copy];
        if (nextBlock == nil) return;

        nextBlock(value);
    }
}

- (void)sendError:(NSError *)e {
    @synchronized (self) {
        void (^errorBlock)(NSError *) = [self.error copy];
        [self.disposable dispose];

        if (errorBlock == nil) return;
        errorBlock(e);
    }
}

- (void)sendCompleted {
    @synchronized (self) {
        void (^completedBlock)(void) = [self.completed copy];
        [self.disposable dispose];

        if (completedBlock == nil) return;
        completedBlock();
    }
}

- (void)didSubscribeWithDisposable:(RACCompoundDisposable *)otherDisposable {
    if (otherDisposable.disposed) return;

    RACCompoundDisposable *selfDisposable = self.disposable;
    [selfDisposable addDisposable:otherDisposable];

    @unsafeify(otherDisposable);

    [otherDisposable addDisposable:[RACDisposable disposableWithBlock:^{
        @strongify(otherDisposable);
        [selfDisposable removeDisposable:otherDisposable];
    }]];
}

可以说只是block的调用吧。

RACPassthroughSubscriber

看不到判断那的代码

上一篇下一篇

猜你喜欢

热点阅读