RAC中的RACReplaySubject

RACSubject的子類,說這個主要為了下篇文章,重寫了RACSubject的四個個重要方法:subscribe,sendNext,sendCompleted, sendError

- (void)sendNext:(id)value {
    @synchronized (self) {
//用數(shù)組存了下sendNext的值
        [self.valuesReceived addObject:value ?: RACTupleNil.tupleNil];
        [super sendNext:value];
//這個數(shù)組有個額度,當超過這個額度,就把前面的清掉。邏輯簡單 
        if (self.capacity != RACReplaySubjectUnlimitedCapacity && self.valuesReceived.count > self.capacity) {
            [self.valuesReceived removeObjectsInRange:NSMakeRange(0, self.valuesReceived.count - self.capacity)];
        }
    }
}

- (void)sendCompleted {
    @synchronized (self) {
//存下commplete的狀態(tài)
        self.hasCompleted = YES;
        [super sendCompleted];
    }
}

- (void)sendError:(NSError *)e {
    @synchronized (self) {
//存下error的狀態(tài)
        self.hasError = YES;
        self.error = e;
        [super sendError:e];
    }
}

好的,這時候如果有人訂閱了這個信號,看看subscribe的操作

- (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
    RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable];

    RACDisposable *schedulingDisposable = [RACScheduler.subscriptionScheduler schedule:^{
        @synchronized (self) {
//好的。如果這時候以前已經(jīng)被訂閱過了,那valuesReceived里面就有值了,就不需要要再走一次didsubribe了,直接sendNext了。這個還是很方便的,如果didsubribe里面有網(wǎng)絡(luò)請求,那多次訂閱不使用這個就會發(fā)很多次請求。
            for (id value in self.valuesReceived) {
                if (compoundDisposable.disposed) return;

                [subscriber sendNext:(value == RACTupleNil.tupleNil ? nil : value)];
            }

            if (compoundDisposable.disposed) return;
            if (self.hasCompleted) {
                [subscriber sendCompleted];
            } else if (self.hasError) {
                [subscriber sendError:self.error];
            } else {
//如果沒被訂閱過,那就老老實實的走一次didsubscriber
                RACDisposable *subscriptionDisposable = [super subscribe:subscriber];
                [compoundDisposable addDisposable:subscriptionDisposable];
            }
        }
    }];

    [compoundDisposable addDisposable:schedulingDisposable];

    return compoundDisposable;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容