高效使用RxJava

Question

场景一:在页面保存时,需要对页面所填写的一些列信息进行判断,确定正确无误后方可保存。

例如:页面上中需要填写:姓名,性别,职业,年薪,住址等信息。

按照常规做法,我们有可能会这么写:

1
2
3
4
5
6
7
8
9
10
if(Util.checkempty(mUserName)){//判断用户名是否为空
return;
}
if(Util.checkempty(mSex)){//判断性别是否为空
return;
}
.....
if(Util.checkempty(mAddress)){//判断住址是否为空
return;
}

而用 Rxjava.combineLatest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//构建被观察者
Observable userNameObservable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(final Subscriber<? super String> subscriber) {
tv.addTextChangedListener(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) {

subscriber.onNext(s.toString());
}

@Override
public void afterTextChanged(Editable s) {

}
});
}
});

Observable sexObservable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(final Subscriber<? super String> subscriber) {
sex.addTextChangedListener(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) {

subscriber.onNext(s.toString());
}

@Override
public void afterTextChanged(Editable s) {

}
});
}
});

Observable.combineLatest(userNameObservable, sexObservable, new Func2<String,String,Boolean>() {

@Override
public Boolean call(String userName, String sex) {
//判断用户名
boolean isUserInvalid = !TextUtils.isEmpty(userName);
//判断性别
boolean isSexInvalid = !TextUtils.isEmpty(sex);
return isUserInvalid && isSexInvalid;
}
}).subscribe(new Action1() {
@Override
public void call(Object o) {//只有都满足条件后才会执行到这里
Log.i("xx","信息:"+o);//可以保存信息了
}
});

场景二:搜索输入,避免多次调用搜索接口,搜索优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(final Subscriber<? super String> subscriber) {
tv.addTextChangedListener(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) {
subscriber.onNext(s.toString());
}

@Override
public void afterTextChanged(Editable s) {

}
});
}
}).filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String s) {

return !TextUtils.isEmpty(s);//过滤为空的
}
}).debounce(1,TimeUnit.SECONDS)
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {

}

@Override
public void onError(Throwable e) {

}

@Override
public void onNext(String s) {
Log.i("xx","搜索字符串::"+s);
}
});
-------------本文结束感谢您的阅读-------------