ReactiveCocoa:配置replayLazily的接收器

时间:2014-05-12 13:04:55

标签: reactive-cocoa

我使用ReactiveCocoa来构成以下结构的复杂信号:

RACSignal* data1FromNetwork = ...;
RACSignal* data1FromNetworkHub = [data1FromNetwork replayLazily];
RACSignal* derivedData = [data1FromNetworkHub flattenMap:...];
RACSignal* data2FromNetwork = ...;
RACSignal* result = [RACSignal combineLatest:@[data1FromNetworkHub, derivedData, data2FromNetwork] reduce:...];

信号data1FromNetwork是作为网络电话实施的,但有多个订阅者 - derivedDatacombineLatest:reduce:。因此,为避免重复网络呼叫,我使用replayLazily创建一个可用于多个订阅的集线器信号。

当我取消result时,所有对集线器信号的订阅都会被释放,但集线器信号与data1FromNetwork之间的订阅本身仍然存在。因此data1FromNetwork不会被取消。基础网络请求完成后,RACReplaySubject内创建的replayLazily会收到通知,此时数据处理将停止,而不会产生任何明显效果。

这是可以接受的,但可以做得更好 - 我也希望取消所有网络活动。这可以使用内置RAC运算符来实现吗?

1 个答案:

答案 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)将被处理掉。