Skip to content

Instantly share code, notes, and snippets.

@milancermak
Created June 13, 2013 16:28
Show Gist options
  • Save milancermak/5775152 to your computer and use it in GitHub Desktop.
Save milancermak/5775152 to your computer and use it in GitHub Desktop.
Question about combining signals in ReactiveCocoa
@interface LoginViewController ()
@property (strong, nonatomic) RACSubject *textFieldReturnPressed;
@property (strong, nonatomic) UITextField *usernameTextField;
@property (strong, nonatomic) UITextField *passwordTextField;
@end
@implementation LoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_textFieldReturnPressed = [RACSubject subject];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self addSubview:self.usernameTextField];
[self addSubview:self.passwordTextField];
RACSignal *validUsername = [self.usernameTextField.rac_textSignal map:^(NSString *username) {
return @(username.length > 0 && [username isAValidEmail]);
}];
RACSignal *validPassword = [self.passwordTextField.rac_textSignal map:^(NSString *password) {
return @(password.length > 0);
}];
[[self.textFieldReturnPressed combineLatestWith:validUsername] subscribeNext:^(RACTuple *values) {
RACTupleUnpack(UITextField *textField, NSNumber *validity) = values;
if (validity.boolValue && [textField isEqual:self.usernameTextField]) {
[self.passwordTextField becomeFirstResponder];
}
}];
[[self.textFieldReturnPressed combineLatestWith:validPassword] subscribeNext:^(RACTuple *values) {
RACTupleUnpack(UITextField *textField, NSNumber *validity) = values;
if (validity.boolValue && [textField isEqual:self.passwordTextField]) {
// start log in process
}
}];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self.textFieldReturnPressed sendNext:textField];
return YES;
}
// other implementation details skipped...
@end
@milancermak
Copy link
Author

Right now, I'm just trying to execute the code on line #34 - basically switch the focus from username text field to password text field when the user hits return (and if the input is correct, as determined by the validUsername signal).

The problem with my code is that because it's using combineWithLatest:, the beginFirstResponder is executed too often. I've tried to adapt the piece of code you suggested to this task, but it has the same effect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment