2015-09-07 33 views
1

這是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失效來實現這一點,但如果不添加任何額外的狀態,這樣做會很好。什麼是正確的方法來做到這一點?

回答

1

我發現了一箇舊後答案通過@賈斯汀 - 斯帕爾 - 夏天: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];