ReactiveCocoa–RACScheduler

bawn發表於2014-08-06

基本資訊

父類 NSObject
子類 RACImmediateScheduler
RACQueueScheduler
RACSubscriptionScheduler
RACTestScheduler
類含義 RAC排程類
遵循的協議
屬性

例子

顯示網路下載的圖片

    RAC(self.imageView, image) = [[RACSignal startEagerlyWithScheduler:[RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground]
                                                                 block:^(id <RACSubscriber> subscriber) {
        NSError *error;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://ww3.sinaimg.cn/bmiddle/7128be06jw1ei4hfthoj3j20hs0bomyd.jpg"]
                                             options:NSDataReadingMappedAlways
                                               error:&error];
        if(error) {
            [subscriber sendError:error];
        }
        else {
            [subscriber sendNext:[UIImage imageWithData:data]];
            [subscriber sendCompleted];
        }
    }] deliverOn:[RACScheduler mainThreadScheduler]];

這段程式碼會在後臺執行緒立即發起一個請求,然後傳遞到主執行緒上更新UI

  • 發起請求: + (RACSignal *)startEagerlyWithScheduler:(RACScheduler *)scheduler block:(void (^)(id<RACSubscriber> subscriber))block;
  • 訊號傳遞: - (RACSignal *)deliverOn:(RACScheduler *)scheduler

方法介紹

    + (RACScheduler *)mainThreadScheduler;

主執行緒排程


    + (RACScheduler *)currentScheduler;

當前佇列排程


    + (RACScheduler *)scheduler;

這方法相當於執行了[RACScheduler schedulerWithPriority:RACSchedulerPriorityDefault];


    + (RACScheduler *)schedulerWithPriority:(RACSchedulerPriority)priority;

指定等級的非同步併發佇列,這個其實呼叫的是

[[RACTargetQueueScheduler alloc] initWithName:name targetQueue:dispatch_get_global_queue(priority, 0)];

其中RACTargetQueueScheduler類的父類是RACQueueScheduler,而且RACQueueScheduler中有個方法是:

- (RACDisposable *)schedule:(void (^)(void))block {
    NSCParameterAssert(block != NULL);
    RACDisposable *disposable = [[RACDisposable alloc] init];
    dispatch_async(self.queue, ^{
        if (disposable.disposed) return;
        [self performAsCurrentScheduler:block];
    });
    return disposable;
}

可以看到最終用的還是dispatch_async的非同步呼叫

相關文章