Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveCocoa: Subscribe only to new values

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?

like image 303
Jasper Blues Avatar asked Mar 07 '14 08:03

Jasper Blues


2 Answers

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
}];
like image 160
joshaber Avatar answered Nov 07 '22 16:11

joshaber


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
}];
like image 36
Vasilii Anisimov Avatar answered Nov 07 '22 18:11

Vasilii Anisimov