Skip to content

Instantly share code, notes, and snippets.

@gshockv
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save gshockv/569118172889103dbb2e to your computer and use it in GitHub Desktop.

Select an option

Save gshockv/569118172889103dbb2e to your computer and use it in GitHub Desktop.
public class RxSignupActivity extends ActionBarActivity {
private static final Pattern emailPattern = Pattern.compile(
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
private EditText editTextUsername;
private EditText editTextEmail;
private Button buttonRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editTextUsername = (EditText) findViewById(R.id.edit_username);
editTextEmail = (EditText) findViewById(R.id.edit_email);
buttonRegister = (Button) findViewById(R.id.btn_register);
buttonRegister.setEnabled(false);
Observable<Boolean> userNameValidator = WidgetObservable.text(editTextUsername)
.map(e -> e.text())
.map(t -> t.length() > 4);
Observable<Boolean> emailValidator = WidgetObservable.text(editTextEmail)
.map(e -> e.text())
.map(t -> emailPattern.matcher(t).matches());
userNameValidator
.distinctUntilChanged()
.doOnNext(b -> Log.d("[Rx]", "Uname " + (b ? " Valid" : "Invalid")))
.map(b -> b ? Color.BLACK : Color.RED)
.subscribe(color -> editTextUsername.setTextColor(color));
emailValidator
.distinctUntilChanged()
.doOnNext(b -> Log.d("[Rx]", "Email " + (b ? " Valid" : "Invalid")))
.map(b -> b ? Color.BLACK : Color.RED)
.subscribe(color -> editTextEmail.setTextColor(color));
Observable<Boolean> registerEnabled
= Observable.combineLatest(userNameValidator, emailValidator, (a, b) -> a && b);
registerEnabled
.distinctUntilChanged()
.doOnNext(b -> Log.d("[Rx]", "Register button " + (b ? " Enabled" : "Disabled")))
.subscribe(enabled -> buttonRegister.setEnabled(enabled));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment