12

I've created an event subscriber in viewDidLoad, as follows:

[RACObserve(_authenticationView.passwordInput.textField, text) subscribeNext:^(NSString* text)
{
     //handle this
}];

This fires whenever the textField.text property changes (expected), however it also fires once when created, or for the intitial value, which is not what I want.

Of course I could filter this out, but I only want to filter the first event out. How do I do this?

Requirements:

  • If the password has a new empty value, present a validation message (can't proceed password empty).
  • If the password has a new non-empty value, talk to remote client.

. . so what's the cleanest way to do this?

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • I'm not ReactiveCocoa user but as far as I understood from the docs of ReactiveCocoa, you should add self(in this case view controller) as an observer and create a new property for NSString * then observe it. In the event method you must set textfield property. – kkocabiyik Mar 07 '14 at 09:10
  • ReactiveCocoa provides a helper `rac_textSignal` method that may be more reliable than observing `text`, since `UITextField`s aren't guaranteed to be KVO compliant for that key (as far as I understand). – Ian Henry Mar 07 '14 at 19:06

2 Answers2

21

If you just want to skip the first value, just stick a -skip:1 in there:

[[RACObserve(_authenticationView.passwordInput.textField, text) skip:1] subscribeNext:^(NSString* text)
{
     //handle this
}];
joshaber
  • 2,465
  • 20
  • 13
  • 2
    ...and this is the canonical way to do this, recommended in the 2.0 migration guide: https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/CHANGELOG.md ...also you're a core ReactiveCocoa contributor, so you knew that already... – Ian Henry Mar 07 '14 at 19:09
1

You can use different approaches:

  1. -skip:1 to skip first value.
[[RACObserve(_authenticationView.passwordInput.textField, text) skip:1] subscribeNext:^(NSString* text) {
    //handle this
}];

  1. -ignore:nil to skip initial nil value.
[[RACObserve(_authenticationView.passwordInput.textField, text) ignore:nil] subscribeNext:^(NSString* text) {
    //handle this
}];

  1. -distinctUntilChanged to skip new values, that equal previous.
[[RACObserve(_authenticationView.passwordInput.textField, text) distinctUntilChanged] subscribeNext:^(NSString* text) {
    //handle this
}];