RAC中的RACScheduler

RACScheduler对GCD进行了封装:
1.获取RACScheduler对象的方式有多种
首先看第一种

+ (instancetype)immediateScheduler {
    static dispatch_once_t onceToken;
    static RACScheduler *immediateScheduler;
    dispatch_once(&onceToken, ^{
        immediateScheduler = [[RACImmediateScheduler alloc] init];
    });
    
    return immediateScheduler;
}

RACImmediateScheduler是RACScheduler的子类,初始化的操作还是会走到父类的初始化方法

//RACImmediateScheduler初始化方法
- (id)init {
    return [super initWithName:@"com.ReactiveCocoa.RACScheduler.immediateScheduler"];
}
//RACScheduler初始化方法
- (id)initWithName:(NSString *)name {
    self = [super init];
    if (self == nil) return nil;

    if (name == nil) {
        _name = [NSString stringWithFormat:@"com.ReactiveCocoa.%@.anonymousScheduler", self.class];
    } else {
        _name = [name copy];
    }

    return self;
}

再看第二种

+ (instancetype)mainThreadScheduler {
    static dispatch_once_t onceToken;
    static RACScheduler *mainThreadScheduler;
    dispatch_once(&onceToken, ^{
        mainThreadScheduler = [[RACTargetQueueScheduler alloc] initWithName:@"com.ReactiveCocoa.RACScheduler.mainThreadScheduler" targetQueue:dispatch_get_main_queue()];
    });
    
    return mainThreadScheduler;
}

RACTargetQueueScheduler的核心操作如下:

- (id)initWithName:(NSString *)name targetQueue:(dispatch_queue_t)targetQueue {
    NSCParameterAssert(targetQueue != NULL);

    if (name == nil) {
        name = [NSString stringWithFormat:@"com.ReactiveCocoa.RACTargetQueueScheduler(%s)", dispatch_queue_get_label(targetQueue)];
    }
//创建一个queue,并且设置其优先级和targetQueue相同
    dispatch_queue_t queue = dispatch_queue_create(name.UTF8String, DISPATCH_QUEUE_SERIAL);
    if (queue == NULL) return nil;

    dispatch_set_target_queue(queue, targetQueue);

    return [super initWithName:name queue:queue];
}

还有几种初始化的方法,也比较简单,下面看RACScheduler的操作

- (RACDisposable *)afterDelay:(NSTimeInterval)delay schedule:(void (^)(void))block {
    return [self after:[NSDate dateWithTimeIntervalSinceNow:delay] schedule:block];
}

子类有不同的实现,但都比较简单。类似

- (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block {
    NSCParameterAssert(date != nil);
    NSCParameterAssert(block != NULL);

    [NSThread sleepUntilDate:date];
    block();

    return nil;
}

还有一个比较难理解的就是scheduleRecursiveBlock,这个放在RACSequence说

你可能感兴趣的:(RAC中的RACScheduler)