观察每一个项目在RACSequence,更新观测时序列具有新项目
问题描述:
这是an earlier question that asked about observing every item in a RACSequence类似的问题 - 正确答案是这样的:观察每一个项目在RACSequence,更新观测时序列具有新项目
RACSignal *valid = [[RACSignal combineLatest:
[self.viewModels map:^id(ViewModel *viewModel) {
return RACObserve(viewModel, state);
}]
]
map:^(RACTuple *states) {
return @([states.rac_sequence all:^BOOL(NSNumber *state) {
return state.unsignedIntegerValue == Completed;
}]);
}
];
我对这个变化是,我想还处理ViewModel实例在序列中添加/删除的情况。我可以通过使存储在实例变量或属性中的RACDisposable失效来实现这一点,但如果不添加任何额外的状态,这样做会很好。什么是正确的方法来做到这一点?
答
我发现了一个旧后答案通过@贾斯汀 - 斯帕尔 - 夏天:https://stackoverflow.com/a/19711002/63580
下面是具体针对我的问题上面为后人版本:
@weakify(self);
RACSignal *enabled = [[RACObserve(self, viewModels)
// Map _each_ array of view models to a signal determining whether the command
// should be enabled.
map:^(NSArray *viewModels) {
RACSequence *selectionSignals = [[viewModels.rac_sequence
map:^(ViewModel *viewModel) {
// RACObserve() implicitly retains `self`, so we need to avoid
// a retain cycle.
@strongify(self);
// Observe each view model's `state` property for changes.
return RACObserve(viewModel, state);
}]
// Ensure we always have one YES for the -and below.
startWith:[RACSignal return:@YES]];
// Sends YES whenever all of the view models are selected, NO otherwise.
return [[RACSignal
combineLatest:selectionSignals]
and];
}]
// Then, ensure that we only subscribe to the _latest_ signal returned from
// the block above (i.e., the observations from the latest `viewModels`).
switchToLatest];