1

这是一个与之前询问观察 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 无效来做到这一点,但如果不添加任何额外的状态,这样做会很棒。这样做的正确方法是什么?

4

1 回答 1

1

我在@justin-spahr-summers 的旧帖子中找到了答案: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];
于 2015-09-08T13:19:49.953 回答