动态 OneToMany ReactiveCocoa 绑定

Dynamic OneToMany ReactiveCocoa binding

我的代码中有类似于以下结构的内容:

// Model
@interface Child : NSObject
@property (nonatomic, assign) CGPoint position;
@end

@interface Father : NSObject
@property (nonatomic, strong) NSArray <Child *> *children; // (0..n)
@end

// ViewModel
@interface FatherViewModel : NSObject
@property (nonatomic, strong) Father *father;
@property (nonatomic, assign) CGPoint averagePositionOfChildren;
@end

在执行期间,每个父成员中children的数量可以改变(在这种情况下,我重新创建了整个NSArray)和每个成员的位置Child也可以改.

ReactiveCocoa 中是否存在将模型中 children 个位置的动态数量映射到 FatherViewModel 中的 averagePositionOfChildren 的优雅解决方案?

是的,我可以看到你选择了两个策略:

1.使用属性

children 使用 MutableProperty,然后为 averagePositionOfChildren 创建映射的 属性。

2。使用 KVO

或者,您可以使用 KVO 来观察 children 中的变化。即,您可以创建一个 DynamicProperty.

请注意,正如您已经指出的那样,这两种情况都会迫使您重新创建整个数组。

如果有人感兴趣,这里遵循我自己的解决方案:

@interface FatherViewModel()
@property (nonatomic, strong) RACDisposable *averageBindingDisposable;
@end

@implementation FatherViewModel
- (instanceType) init {
self = [super init];
...
...
RACSignal *signalOfSignals = [RACObserve(self, father.children)
                         map:^RACSignal *(NSArray <Child *> *setOfChildren) {
                             NSArray <RACSignal *> *arrayOfSignal = [[[setOfChildren rac_sequence]
                                                                      map:^RACSignal *(Child *child) {
                                                                          return RACObserve(child, position);
                                                                      }]
                                                                     array];
                             return [RACSignal combineLatest:arrayOfSignal];
                         }];

[self.averageBindingDisposable dispose];
self.averageBindingDisposable = [[[signalOfSignals flatten]
                  map:^NSValue *(RACTuple *tuple) {
                      NSArray <NSValue *> *arrayOfWrappedCGPoints = tuple.allObjects;
                      CGPoint avg = CGPointZero;
                      // Compute here the average of the points in the array
                      return [NSValue valueWithPoint: avg];
                  }]
                  setKeyPath:@"averagePositionOfChildren" onObject: self];
}];

return self;
}
...
@end