我试图熟悉 RxBinding 以及如何将它应用于简单的表单。我想知道是否有办法创建一个执行检查和更新模型的 Action1。如果我不够清楚,我希望下面的代码可以帮助您理解我的意思。
Observable<CharSequence> nameObservable = RxTextView.textChanges(name).share();
Action1<CharSequence> validateAction;
Observable<CharSequence> surnameObservable = RxTextView.textChanges(surname).share();
Observable<CharSequence> emailObservable = RxTextView.textChanges(mail).share();
validateAction = new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
if(state.nameState && state.surnameState && state.emailState)
submit.setBackgroundColor(getResources().getColor(R.color.green));
else
submit.setBackgroundColor(getResources().getColor(R.color.blue));
}
};
Subscription nameState = nameObservable
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
Log.d("Length","Len : " + charSequence.length());
if(charSequence.length() > 5)
state.nameState = true;
else
state.nameState = false;
}
});
Subscription surnameState = surnameObservable
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
Log.d("Length","Len : " + charSequence.length());
if(charSequence.length() > 5)
state.surnameState = true;
else
state.surnameState = false;
}
});
Subscription mailState = emailObservable
.subscribe(new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
Log.d("Length","Len : " + charSequence.length());
if(charSequence.length() > 5)
state.emailState = true;
else
state.emailState = false;
}
});
Subscription nameValidate = nameObservable.subscribe(validateAction);
Subscription surnameValidate = surnameObservable.subscribe(validateAction);
Subscription mailValidate = emailObservable.subscribe(validateAction);
我创建了一个 Action1,其职责是检查模型的状态并更改按钮的颜色,创建与 Observable 数量相等的订阅并将其作为参数传递。
例如像这样的东西
Action1<CharSequence> lengthCheck = new Action1<CharSequence>() {
@Override
public void call(CharSequence charSequence) {
if(field is name){
if(charSequence.length() > 5)
...
}
...
}
};
所以我的问题是,对于检查长度的 Action1,有没有办法成功完成与此类似的事情?像这样进行检查甚至是正确的地方吗?对我来说,我有完全相同的代码,复制和粘贴三遍,只做很少的改动,这似乎很愚蠢。
非常感谢您的时间。