过滤操作符也是在上游和下游之间插入,主要用来进行数据的过滤
主要实现过程如下:
1,filter操作符
Observable.just("zhan","san","li","si")
.filter(new Predicate<String>() {
@Override
public boolean test(String s) throws Exception {
//return true;//不过滤,默认全部都会答应
//return false;//就全部不打印
return true;
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.d("MainActivity","accept:"+s);
}
});
2,take操作符
//定时器,每个2秒执行一次
Observable.interval(2,TimeUnit.SECONDS)
.take(8)//增加执行次数达到8 停止下来
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
Log.d("MainActivity","accept:"+aLong);
}
});
3,distinct操作符
主要用于过滤重复的数据
//过滤重复的
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(1);
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(1);
emitter.onNext(3);
emitter.onNext(3);
}
}).distinct()
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
Log.d("MainActivity","accept:"+integer);
}
});
4,elementAt(index,“defaultValue”)操作符的使用
指定过滤的内容,可以设置默认值,如果找不到就使用默认的值,发射给下游
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
emitter.onNext("zhangsan");
emitter.onNext("李四");
emitter.onNext("赵武");
emitter.onNext("zhangsan");
}
}).elementAt(1,"zhasss")
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.d("MainActivity","accept:"+s);
}
});