我的 ViewController 上有一个 NSArray 的 ViewModel 对象:
@property(非原子,强)NSArray *viewModels;
ViewModel 对象看起来像这样:
@interface ViewModel : NSObject
@property (nonatomic) BOOL isSelected;
@end
我正在尝试在 RACCommand 的 init 方法上为启用信号创建 RACSignal:
- (id)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal * (^)(id input))signalBlock
如果选择了 0 个 viewModel 对象,或者选择的 viewModel 数量等于 viewModel 的总数,则此信号将告诉命令启用。
我可以创建一个 RACSequence,它将为我提供由以下代码选择的 viewModel 对象:
RACSequence *selectedViewModels = [[self.viewModels.rac_sequence
filter:^BOOL(ViewModel *viewModel) {
return viewModel.isSelected == YES;
}]
map:^id(ViewModel *viewModel) {
return viewModel;
}];
我将如何创建有效信号?
观察所有最新的视图模型(以及only最新的视图模型)对于更改,我们需要在每次数组更改时设置新的 KVO 观察。
表示这一点的最自然的方式是使用信号的信号。每个“内部”信号代表对一个版本的一组观察结果viewModels
,然后我们将使用-switchToLatest
确保只有最新的信号才生效:
@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 `isSelected` property for changes.
return RACObserve(viewModel, isSelected);
}]
// 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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)