观察RACSequence中的每一项 [英] Observe every item in RACSequence
问题描述
我在 ParentViewModel 上有一个方法,它返回 ViewModel 对象的 RACSequence,如下所示:
I have a method on ParentViewModel which returns an RACSequence of ViewModel objects like so:
- (RACSequence *) viewModels
{
return [self.models.rac_sequence map:^id(Model *model) {
return [[ViewModel alloc] initWithModel: model];
}];
}
每个 ViewModel 都有一个 state 属性,该属性是一个枚举并具有 3 个状态:NotStarted、InProgress 和 Completed.当我序列中的所有 ViewModel 都具有 Completed 状态时,我知道 ParentViewModel 是有效的.我在 ParentViewModel 上有一个 validSignal,我想从 viewModels 序列中推导出有效的事实.目前我有这个代码:
Each of the ViewModels has a state property on which is an enum and has 3 states: NotStarted, InProgress and Completed. When all the ViewModels in my sequence have the state Completed I know ParentViewModel is valid. I have a validSignal on the ParentViewModel which I want to derive the fact that is valid from the viewModels sequence. At the moment I have this code:
BOOL valid = [[self viewModels] all:^BOOL(ViewModel *vm) {
return vm.state == Completed;
}];
如果序列中的所有 ViewModel 都有效,它会给我一个指示.然后,我如何将其转换为 RACSignal,每当其中一个 ViewModel 上的 state 属性发生更改时,该 RACSignal 都会更新?
Which gives me an indicator if all ViewModels in the sequence are valid. How can I then turn this into a RACSignal which will update every time the state property on one of the ViewModels changes?
推荐答案
您首先需要将 state
转换为 RACSignal
,然后一切就变得简单了.
You need first to turn state
into a RACSignal
, and then everything is easy from that point.
最终代码如下:
RACSignal *valid = [[RACSignal combineLatest:
[[self viewModels] map:^id(ViewModel *viewModel) {
return RACAbleWithStart(viewModel, state);
}]
]
map:^(RACTuple *states) {
return @([states.rac_sequence all:^BOOL(NSNumber *state) {
return state.unsignedIntegerValue == Completed;
}]);
}
];
第一个块将您的每个视图模型映射到一个信号,该信号观察 state
属性(将起始值作为信号的第一个值).
The first block maps each of your view models into a signal that observes the state
property (with the starting value as first value of the signal).
combineLatest:
将采用 RACSignals
的集合,并创建一个新信号,每当其中一个底层信号发生变化时都会触发该信号,并发送一个 RACTuple
与每个信号的值.
combineLatest:
will take a collection of RACSignals
and will create a new signal that fires everytime one of the underlaying signals changes, and sends a RACTuple
with the value of each signal.
那个RACTuple
然后被转换成一个RACSequence
,我们可以生成一个@YES
或@NO
的值code> 取决于所有值是否Completed
.
That RACTuple
is then converted into a RACSequence
, and we can generate a value of @YES
or @NO
depending if all the values are Completed
or not.
我认为结果就是您正在寻找的信号.
I think the result is the signal you were looking for.
(免责声明:我是 ReactiveCocoa 的新手,所以可能有更简单的方法).
(Disclaimer: I’m new to ReactiveCocoa, so there may be an easier way).
这篇关于观察RACSequence中的每一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!