在FilterActivity里面
2.讲解
1.filter
过滤,false的表示过滤掉,true的表示保留 在 这 “三鹿”, “合生元”, “飞鸽” 三个中,三鹿保留,其他两个都过滤掉,既只打印“三鹿”。
Observable.just("三鹿", "合生元", "飞鸽")
.filter(new Predicate<String>() {
@Override
public boolean test(String s) throws Throwable {
Log.d(TAG, "test: 多少次");
if (s.equals("三鹿")) {
return true;
} else {
return false;
}
}
})
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Throwable {
Log.d(TAG, "accept: " + s);
}
});
2.take
可以限制打印多少个,下面的只打印8个(本来无限打印)
Observable.interval(1, TimeUnit.SECONDS)
.take(8)
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Throwable {
Log.d(TAG, "accept: "+aLong);
}
});
3.distinct
表示去重 本来打印全部,现在去掉重复的,然后打印
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(1);
emitter.onNext(3);
emitter.onNext(5);
emitter.onNext(4);
emitter.onComplete();
}
})
.distinct()
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.d(TAG, "accept: "+integer);
}
});
打印结果为:1,2,3,5,4
4.elementAt
指定位置打印。下面打印的是葵花宝典2。0表示打印第一个,2表示打印第三个
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
emitter.onNext("九阴真经");
emitter.onNext("葵花宝典");
emitter.onNext("葵花宝典2");
emitter.onNext("乾坤大罗伊");
emitter.onNext("独孤九剑");
emitter.onComplete();
}
})
.elementAt(2,"默认典")
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Throwable {
Log.d(TAG, "accept: "+s);
}
});
|