我有3个依赖信号,我想将它们的值组合成一个对象。我想出了两个选择。
选项1:
+ (RACSignal *)createObject {
RACSignal *paramsSignal = [[[self class] createObject1] flattenMap:^RACStream *(NSString *object1) {
return [[[self class] createObject2:object1] flattenMap:^RACStream *(NSString *object2) {
return [[[self class] createObject3:object2] flattenMap:^RACStream *(NSString *object3) {
return [RACSignal return:RACTuplePack(object1, object2, object3)];
}];
}];
}];
return [paramsSignal map:^id(RACTuple *tuple) {
return [[CombinedObject alloc] initWithO1: tuple.first O2: tuple.second O3: tuple.third];
}];
}
我不喜欢所有的嵌套和封闭。
选项2:
+ (RACSignal *)createObject {
RACSignal *paramsSignal = [[[[self class] createObject1] flattenMap:^id(NSManagedObjectModel *object1) {
return [RACSignal combineLatest:@[[RACSignal return:object1], [[self class] createObject2:object1]]];
}] flattenMap:^RACStream *(RACTuple *tuple) {
return [RACSignal combineLatest:@[[RACSignal return:tuple.first], [RACSignal return:tuple.second], [[self class] createObject3:tuple.second]]];
}];
return [paramsSignal map:^id(RACTuple *tuple) {
return [[CombinedObject alloc] initWithO1: tuple.first O2: tuple.second O3: tuple.third];
}];
}
没有嵌套或闭包,但是过多的元组和对象正在通过每个信号......
所以我想知道是否有更优雅的解决方案我不存在。
感谢。
答案 0 :(得分:0)
堆栈式方法怎么样?
- (NSArray *) createPhases {
return @[@selector(createObject1:), @selector(createObject2:), @selector(createObject3:)];
}
...
+ (RACSignal *)createObject {
NSMutableArray *stack = [NSMutableArray new];
for (SEL phase: [self createPhases]) {
stack = [[[self class] performSelector:phase withObject:stack] flattenMap:^RACStream *(NSString *append) {
return [stack arrayByAddingArray:@[append]]; // or with some other manipulations
}];
}
return [self withObjects:stack map:^id(NSArray *stack) {
return [[CombinedObject alloc] initWithObjects:stack];
}];
}
- (...) createObject1:(NSArray *)chain {
// here chain will be empty, actually (@[])
return ... // create object 1
}
- (...) createObject2:(NSArray *)chain {
// here chain will be @[object1]
return [... ... withObject1:[chain lastObject]]; // create object 2
}
- (...) createObject3:(NSArray *)chain {
// here chain will be @[object1, object2]
return [... ... withObject2:[chain lastObject]]; // create object 3
}