使用 ReactiveCocoa 将信号值收集到数组中
Collect signal values to an array using ReactiveCocoa
我使用 ReactiveCocoa 来记录数组中的点击:
@interface ViewController : UIViewController
@property (strong, nonatomic) NSArray *first10Taps;
@property (strong, nonatomic) UITapGestureRecognizer *tapGesture;
@end
@implementation ViewController
- (void) viewDidLoad
{
[super viewDidLoad];
RACSignal *tapSignal = [[self.tapGesture rac_gestureSignal] map:^id(UITapGestureRecognizer *sender) {
return [NSValue valueWithCGPoint:[sender locationInView:sender.view]];
}];
// This signal will send the first 10 tapping positions and then send completed signal.
RACSignal *first10TapSignal = [tapSignal take:10];
// Need to turn this signal to a sequence with the first 10 taps.
RAC(self, first10Taps) = [first10TapSignal ...];
}
@end
如何将此信号转为阵列信号?
每次发送新值时我都需要更新数组。
RACSignal
上有一个方法叫做 collect
。它的文档说:
Collects all receiver's next
s into a NSArray. Nil values will be
converted to NSNull. This corresponds to the ToArray
method in Rx.
Returns a signal which sends a single NSArray when the receiver
completes successfully.
所以你可以简单地使用:
RAC(self, first10Taps) = [first10TapSignal collect];
感谢 Michał Ciuba 的回答。使用-collect
只会在上行信号完成时才发送采集值。
我找到了使用 -scanWithStart:reduce:
产生信号的方法,该信号会在每次发送 next
值时发送集合。
RAC(self, first10Taps) = [firstTapSetSignal scanWithStart:[NSMutableArray array] reduce:^id(NSMutableArray *collectedValues, id next) {
[collectedValues addObject:(next ?: NSNull.null)];
return collectedValues;
}];
我使用 ReactiveCocoa 来记录数组中的点击:
@interface ViewController : UIViewController
@property (strong, nonatomic) NSArray *first10Taps;
@property (strong, nonatomic) UITapGestureRecognizer *tapGesture;
@end
@implementation ViewController
- (void) viewDidLoad
{
[super viewDidLoad];
RACSignal *tapSignal = [[self.tapGesture rac_gestureSignal] map:^id(UITapGestureRecognizer *sender) {
return [NSValue valueWithCGPoint:[sender locationInView:sender.view]];
}];
// This signal will send the first 10 tapping positions and then send completed signal.
RACSignal *first10TapSignal = [tapSignal take:10];
// Need to turn this signal to a sequence with the first 10 taps.
RAC(self, first10Taps) = [first10TapSignal ...];
}
@end
如何将此信号转为阵列信号?
每次发送新值时我都需要更新数组。
RACSignal
上有一个方法叫做 collect
。它的文档说:
Collects all receiver's
next
s into a NSArray. Nil values will be converted to NSNull. This corresponds to theToArray
method in Rx. Returns a signal which sends a single NSArray when the receiver completes successfully.
所以你可以简单地使用:
RAC(self, first10Taps) = [first10TapSignal collect];
感谢 Michał Ciuba 的回答。使用-collect
只会在上行信号完成时才发送采集值。
我找到了使用 -scanWithStart:reduce:
产生信号的方法,该信号会在每次发送 next
值时发送集合。
RAC(self, first10Taps) = [firstTapSetSignal scanWithStart:[NSMutableArray array] reduce:^id(NSMutableArray *collectedValues, id next) {
[collectedValues addObject:(next ?: NSNull.null)];
return collectedValues;
}];