4

ViewController に ViewModel オブジェクトの NSArray があります。

@property (非アトミック、強力) NSArray *viewModels;

ViewModel オブジェクトは次のようになります。

@interface ViewModel : NSObject

@property (nonatomic) BOOL isSelected;

@end

RACCommand の init メソッドで enabledSignal の RACSignal を作成しようとしています。

- (id)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal * (^)(id input))signalBlock

このシグナルは、選択された viewModel オブジェクトが 0 であるか、選択された viewModel の数が viewModel の総数と等しい場合に有効になるように Command に指示します。

このコードで選択された viewModel オブジェクトを提供する RACSequence を作成できます。

RACSequence *selectedViewModels = [[self.viewModels.rac_sequence

                                        filter:^BOOL(ViewModel *viewModel) {
                                            return viewModel.isSelected == YES;
                                        }]

                                       map:^id(ViewModel *viewModel) {
                                           return viewModel;
                                       }];

有効な信号を作成するにはどうすればよいですか?

4

1 に答える 1

7

最新のすべてのビュー モデル (および最新のビュー モデルのみ) の変更を監視するには、配列が変更されるたびに新しい KVO 監視を設定する必要があります。

これを表現する最も自然な方法は、シグナルのシグナルを使用することです。各「内部」シグナルは、 の 1 つのバージョンでの一連の観測を表し、最新のシグナルのみが有効になるように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];
于 2013-10-31T15:46:42.570 に答える