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;
}