I am using android data binding and i want to create an observable from the edit text data so i can perform operations on it using rxjava. This is my code.
The XML
<EditText
android:id="@+id/edit_text_username"
android:layout_width="match_parent"
android:addTextChangedListener="@{viewModel.getUsername}"
android:background="@drawable/border_edit_top"
android:drawableLeft="@drawable/ic_person_white_24px"
android:drawablePadding="10dp"
android:drawableStart="@drawable/ic_person_white_24px"
android:hint="@string/username"
android:inputType="text"
android:paddingEnd="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingStart="10dp"
app:layout_heightPercent="10%" />
The ViewModel Class
public TextWatcher getUsername() {
return new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("username", s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
I have 3 such edit texts on which i want to use the combinelatest operator of rx java for form validations.How exactly do i go about implementing rx java in this scenario?
You can use RxBinding. This example could help you.
//Validate username field
Observable<Boolean> usernameObservable = RxTextView.textChanges(usernameEditText)
.map(username -> StringUtils.isNotBlank(username) && Validators.validateUsername(username.toString())).skip(1);
//Validate password field
Observable<CharSequence> passwordObservable = RxTextView.textChanges(passwordEditText).skip(1);
//Validate confirm password field
Observable<CharSequence> confirmPasswordObservable = RxTextView.textChanges(confirmPasswordEditText)
.skip(1);
//Validate password matches field
Observable<Boolean> passwordMatcherObservable = Observable.combineLatest(passwordObservable, confirmPasswordObservable,
(password, confirmPassword) -> password.toString().equals(confirmPassword.toString())).skip(1);
Observable.combineLatest(passwordMatcherObservable, usernameObservable,
(passwordMatch, isUsernameValid) -> passwordMatch && isUsernameValid)
.distinctUntilChanged()
.subscribe(valid -> createAccountBtn.setEnabled(valid));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With