objective-creactive-cocoareactive-cocoa-3

Dynamic OneToMany ReactiveCocoa binding


I have something similar to the following structure in my code:

// 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

During execution, number of children in each Father member can change (in this case I recreate the whole NSArray) and position of each Child can also change.

Does any elegant solution in ReactiveCocoa exist to map the dynamic number of children positions in the model to averagePositionOfChildren in FatherViewModel?


Solution

  • Yes, I can see you choose two strategies:

    1. Use properties

    Use a MutableProperty for children and then create a mapped property for averagePositionOfChildren.

    2. Use KVO

    Alternatively, you can use KVO to watch changes in children. I.e., you can create a DynamicProperty.

    Note that both scenarios would force you to recreate the whole array, as you already noted.