我使用ReactiveCocoa来构成以下结构的复杂信号:
RACSignal* data1FromNetwork = ...;
RACSignal* data1FromNetworkHub = [data1FromNetwork replayLazily];
RACSignal* derivedData = [data1FromNetworkHub flattenMap:...];
RACSignal* data2FromNetwork = ...;
RACSignal* result = [RACSignal combineLatest:@[data1FromNetworkHub, derivedData, data2FromNetwork] reduce:...];
信号data1FromNetwork
是作为网络电话实施的,但有多个订阅者 - derivedData
和combineLatest:reduce:
。因此,为避免重复网络呼叫,我使用replayLazily
创建一个可用于多个订阅的集线器信号。
当我取消result
时,所有对集线器信号的订阅都会被释放,但集线器信号与data1FromNetwork
之间的订阅本身仍然存在。因此data1FromNetwork
不会被取消。基础网络请求完成后,RACReplaySubject
内创建的replayLazily
会收到通知,此时数据处理将停止,而不会产生任何明显效果。
这是可以接受的,但可以做得更好 - 我也希望取消所有网络活动。这可以使用内置RAC运算符来实现吗?
答案 0 :(得分:2)
它可能表示为使用-[RACMulticastConnection autoconnect]
:
RACSignal* data1FromNetwork = ...;
RACSignal* data1FromNetworkHub = [[data1FromNetwork publish] autoconnect];
// Or below if you want replaying behavior.
// RACSignal* data1FromNetworkHub = [[data1FromNetwork multicast:RACReplaySubject.subject] autoconnect];
RACSignal* derivedData = [data1FromNetworkHub flattenMap:...];
RACSignal* data2FromNetwork = ...;
RACSignal* result = [RACSignal combineLatest:@[data1FromNetworkHub, derivedData, data2FromNetwork] reduce:...];
当-autoconnect
返回的信号没有订户时,基础信号(在这种情况下为data1FromNetwork
)将被处理掉。