RxJava操作符应用
引入库:
api("io.reactivex.rxjava3:rxjava:3.1.0")
api('io.reactivex.rxjava3:rxandroid:3.1.0')
操作符分类
创建操作符
复杂数据遍历
just
fromArray
fromIterable
range
定时任务
interval
intervalRange
嵌套回调异步事件
create
延迟任务
defer
timer
变换操作符
变换
map
flatMap
concatMap
合并操作符
组合多个被观察者,合并事件
concatArray(发送事件--串行)
concatDelayError
megerArray(发送事件--并行)
megerArrayDelayError
组合多个被观察者,合并为一个被观察者
zip
combineLatest
发送事件前追加其他事件
startWithArray
组合多个事件为一个事件
reduce
collect
汇总发送事件数量
count
过滤操作符
指定过滤条件,过滤需要的事件/数据
filter
过滤指定类型的事件/数据
ofType
过滤条件不满足的事件/数据
skip
过滤掉重复的事件/数据
distinct
distinctUntilChanged
按时间或者数量过滤事件/数据
take
过滤指定位置的事件
elementAt
按事件段过滤事件
throttleFirst
throttleLast
条件操作符
判断所有事件是否满足
all
发送的事件判断条件不满足时,就会终止后续事件接收
takeWhile
发送的事件判断条件不满足时,才接收后续的事件
skipWhile
过滤事件(同filter)
takeUntil
接收判断条件满足之外的事件
skipUntil
判断2个被观察者发生的事件是否一样
sequenceEqual
判断发送的数据里面是否包含指定数据
contains
判断发送的数据是否为空
isEmpty
多个被观察者,只接收"第一个成功发送数据的被观察者"
amb
其他功能操作符
常用的do系列操作符
doOnEach
doOnSubscribe
doOnNext
doAfterNext
doOnComplete
doOnErro
错误/异常处理
抓捕异常并反馈特殊的结果&正常终止
onErrorRetuturn
抓捕异常并返回一个新的事件
onErrorResumeNext
异常重试
retry
事件重发
repeat
repeatWhen
repeatUntil
延迟发送被观察者的事件
delay
发送事件超时处理
timeout
一、创建操作符
1. **just** 将一个或多个对象转换成发射这个或这些对象的一个Observable
2. **from** 将一个Iterable、Future或者一个数组转换成一个Observable
3. **create** 使用一个函数从头创建一个Observable
4. **defer** 只有当订阅者订阅才创建Observable,为每个订阅创建一个新的Observable
5. **range** 创建一个发射指定范围的整数序列的Observable
6. **interval** 创建一个按照给定的时间间隔发送的整数序列的Observable
7. **timer** 创建一个指定的延时之后发射单个数据的Observable
8. **empty** 创建一个什么都不做直接通知完成的Observable
9. **error** 创建一个什么都不做直接通知错误的Observable
10. **never** 不发射任何数据
1.create
subscribe回调有两种,一种是Observer回调回所有方法,一种是Consumer,可以回调自己需要的方法
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
emitter.onNext("hahahhahhh");
int a = 0;
int b = 11/a; //会抛异常,回调到onError方法
}
}).subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull String s) {
System.out.println(s);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println(e.getMessage());
}
@Override
public void onComplete() {
}
});
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
emitter.onNext("hahahhahhh");
int a = 0;
int b = 11/a; //会抛异常,回调到onError方法
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Throwable {
System.out.println(s);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Throwable {
System.out.println("我是异常"+throwable.getMessage());
}
});
2.just和from
just操作符:将某个对象转化为Observable对象,并且将其发射出去,可以使一个数字、一个字符串、数组、Iterate对象等,是一种非常快捷的创建Observable对象的方法~
Observable.just(mList).subscribe(new Observer<List<String>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull List<String> strings) {
System.out.println(strings);
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
Observable.just(1,2,3,4,5).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
from操作符 :用来将某个对象转化为Observable对象,并且依次将其内容发射出去,from的接收值可以是集合或者数组,这个类似于just,但是just会将这个对象整个发射出去。比如说一个含有3个元素的集合,from会将集合分成3次发射,而使用just会发射一次来将整个的数组发射出去~
Observable.fromArray(mList).subscribe(new Consumer<List<String>>() {
@Override
public void accept(List<String> strings) throws Throwable {
System.out.println(strings);
}
});
3.defer操作符
Defer操作符只有当有Subscriber来订阅的时候才会创建一个新的Observable对象,也就是说每次订阅都会得到一个刚创建的最新的Observable对象,这可以确保Observable对象里的数据是最新的,而just则没有创建新的Observable对象
Consumer<String> action1 = new Consumer<String>() {
@Override
public void accept(String s) throws Throwable {
System.out.println(s);
}
};
// defer
Observable<String> defer = Observable.defer(new Supplier<ObservableSource<? extends String>>() {
@Override
public ObservableSource<? extends String> get() throws Throwable {
Object o = new Object();
return Observable.just("defer : hashCode = " + o.hashCode());
}
});
defer.subscribe(action1);
defer.subscribe(action1);
defer.subscribe(action1);
// just
Observable<String> just = Observable.just("just : hashCode = " + new Object().hashCode());
just.subscribe(action1);
just.subscribe(action1);
just.subscribe(action1);
打印:
defer : hashCode = 1865127310
defer : hashCode = 292938459
defer : hashCode = 917142466
just : hashCode = 1993134103
just : hashCode = 1993134103
just : hashCode = 1993134103
从输出结果可以看出来,defer订阅了三次,但是每次的地址值都发生了变化,而just则三次的地址值是同样的,从而验证了上面的结论。
4.range操作符
Range操作符根据输入的初始值【start】和数量【count】发射count次、大于等于start的值~
Observable.range(100,10).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println(integer);
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
打印结果:
100
101
102
103
104
105
106
107
108
109
onComplete
Process finished with exit code 0
5.interval操作符
Interval所创建的Observable对象会从0开始,每隔固定的时间发射一个数字,需要注意的是这个对象是运行在computation Scheduler,需要在安卓项目运行,所以要更新UI需要在主线程中进行订阅~,在项目中,可以做定时器使用
Observable.interval(1, TimeUnit.SECONDS)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Throwable {
Log.e("---->","计时 "+aLong);
}
});
6.timer操作符
Timer会在指定时间后发射一个数字0,注意其也是运行在computation Scheduler~,类似于postdelay
Log.e("---->","倒计时 "+10 +"秒后执行");
Observable.timer(10,TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Throwable {
Log.e("---->","开始执行");
}
});
7.empty操作符
创建一个空的,不会发射任何事件(数据)的Observable
Observable<String> empty = Observable.empty();
empty.subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull String s) {
System.out.println("onNext: "+s);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError :"+e.getMessage());
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
8.never操作符
创建一个Observable不发射任何数据、也不给订阅ta的Observer发出任何通知~
与empty的区别是,never不执行onComplete
Observable<String> never = Observable.never();
never.subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull String s) {
System.out.println("onNext: "+s);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError :"+e.getMessage());
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
9.error操作符
返回一个Observable,当有Observer订阅ta时直接调用Observer的onError方法终止
Observable<String> error = Observable.error(new Throwable("Observable error"));
error.subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull String s) {
System.out.println("onNext: "+s);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError :"+e.getMessage());
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
10.repeat操作符
Repeat会将一个Observable对象重复发射,接收值是发射的次数,依然订阅在 computation Scheduler~
Observable.just(1,2).repeat(10).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println("accept : "+integer);
}
});
11.delay操作符
功能与timer操作符一样,但是delay用于在事件中,可以延迟发送事件中的某一次发送~
必须在安卓项目中执行:
Observable.just(1,2).delay(2, TimeUnit.SECONDS).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","开始执行" +integer);
}
});
二、变换操作符
**> Map
FlatMap
GroupBy
GroupBy
Buffer
Scan
Window…**
1.Map操作符
映射,一般用于对原始的数据进行加工处理,返回一个加工过后的数据~
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
emitter.onNext("https://www.baidu.com");
}
}).map(new Function<String, URL>() {
@Override
public URL apply(String s) throws Throwable {
return new URL(s);
}
}).subscribe(new Consumer<URL>() {
@Override
public void accept(URL url) throws Throwable {
System.out.println(url);
}
});
2.FlatMap操作符
扁平映射,作用是将一个原始Observable发射的数据进行变化,输出一个或多个Observable,然后将这些Observable发射的数据平坦化的放进一个单独的Observable(参数一般是Function)~
Observable.just("register").flatMap(new Function<String, ObservableSource<?>>() {
@Override
public ObservableSource<String> apply(String s) throws Throwable {
System.out.println(s);
System.out.println("注册成功");
return Observable.just("请求登录");
}
}).subscribe(new Observer<Object>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull Object o) {
System.out.println(o);
System.out.println("登录成功 " );
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
3.concatMap操作符
concatMap
操作符的功能和flatMap
是非常相似的,只是有一点,**concatMap 最终输出的数据序列和原数据序列是一致,它是按顺序链接Observables,而不是合并(flatMap用的是合并)。
我们来看一个例子:**Observable 发射5个数据(1,2,3,4,5),然后分别
用flatMap
和concatMap
对它执行一个变换( *10),然后再输出结果序列。
Observable.fromArray(1,2,3,4,5)
.concatMap(new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer integer) throws Throwable {
int delay = 0;
if(integer == 3){
delay = 500;//延迟500ms发射
}
return Observable.just(integer *10).delay(delay, TimeUnit.SECONDS);
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","concatMap :"+integer);
}
});
Observable.fromArray(1,2,3,4,5)
.flatMap(new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer integer) throws Throwable {
int delay = 0;
if(integer == 3){
delay = 500;//延迟500ms发射
}
return Observable.just(integer *10).delay(delay, TimeUnit.SECONDS);
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","flatMap :"+integer);
}
});
得出结论,concatMap会顺序打印,flatMap打印是无序的
4.Buffer操作符
可以简单的理解为缓存,它可以批量或者按周期性从Observable收集数据到一个集合,然后把这些数据集合打包发射,而不是一次发射一个数据~
Observable.range(0,10)
.buffer(3)
.subscribe(new Consumer<List<Integer>>() {
@Override
public void accept(List<Integer> integers) throws Throwable {
System.out.println(integers);
}
});
5.GroupBy操作符
分组 筛选
Observable.range(0,10)
.groupBy(new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) throws Throwable {
return integer/2;
}
}).subscribe(new Consumer<GroupedObservable<Integer, Integer>>() {
@Override
public void accept(GroupedObservable<Integer, Integer> integerIntegerGroupedObservable) throws Throwable {
System.out.println(integerIntegerGroupedObservable.getKey());
}
});
6.Sacn操作符
sacn操作符是遍历源Observable产生的结果,通过自定义转换规则,依次输出结果给订阅者,
Observable.range(0,5)
// 第一个参数是上次的结算结果,
// 第二个参数是当此的源observable的输入值
.scan(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer integer, Integer integer2) throws Throwable {
return integer+integer2;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
7.Window操作符
可以批量或者按周期性从Observable收集数据到一个集合,然后把这些数据集合打包发射,而不是一次发射一个数据,类似于Buffer,但Buffer发射的是数据,Window发射的是Observable~
Observable.range(0,5)
.window(2)
.subscribe(new Consumer<Observable<Integer>>() {
@Override
public void accept(Observable<Integer> integerObservable) throws Throwable {
System.out.println("onOutsideNext -->" + integerObservable);
integerObservable.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
}
});
三、合并操作符
1.merge(),concat ()操作符
merge操作符是把多个Observable合并成一个进行发射。merge可能会让合并到Observable的数据顺序发生错乱(组合被观察者数量<=4个)(并行无序)
mergeArray操作符和merge作用一样,但不同的是组合被观察者数量>4个)(并行无序)
Observable observable1 = Observable.just(1, 2, 3);
Observable observable2 = Observable.just("苹果", "香蕉", "橘子");
Observable.merge(observable1,observable2)
.subscribe(new Consumer() {
@Override
public void accept(Object o) throws Throwable {
System.out.println("merge:"+ o.toString());
}
});
concat操作符也是把多个Observable合并成一个进行发射。但concat则保证合并的每个Observable的事件按顺序发射出去。(组合被观察者数量<=4个)(串行有序)
concatArray操作符和concat作用一样,但不同的是组合被观察者数量>4个)(串行有序)
Observable observable1 = Observable.just(1, 2, 3);
Observable observable2 = Observable.just("苹果", "香蕉", "橘子");
Observable observable3 = Observable.just(false,true);
Observable.concat(observable1,observable2,observable3)
.subscribe(new Consumer() {
@Override
public void accept(Object o) throws Throwable {
System.out.println("concat:"+ o.toString());
}
});
2.concatArrayDelayError()/mergeArrayDelayError() 操作符
这两个操作符的作用是: 使用concat()和merge()操作符时,若其中一个被观察者发送onError事件,则会马上终止其它被观察者继续发送事件。所以呐,这时使用concatError()/mergeDelayError()事件可以使onError事件推迟到其它被观察者发送事件结束后在再触发
Observable
.concatArrayDelayError(Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(1);
emitter.onNext(2);
emitter.onError(new NullPointerException());
emitter.onNext(3);
emitter.onNext(4);
}
}), Observable.just(5, 6))
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
System.out.println( "收到消息 "+String.valueOf(integer));
}
@Override
public void onError(Throwable e) {
System.out.println("cDelayError"+ "onError");
System.out.println(e.getMessage());
}
@Override
public void onComplete() {
System.out.println( "onComplete");
}
});
用法一模一样,输出也一样
Observable
.mergeArrayDelayError(Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(1);
emitter.onNext(2);
emitter.onError(new NullPointerException());
emitter.onNext(3);
emitter.onNext(4);
}
}), Observable.just(5, 6))
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
System.out.println( "收到消息 "+String.valueOf(integer));
}
@Override
public void onError(Throwable e) {
System.out.println("cDelayError"+ "onError");
System.out.println(e.getMessage());
}
@Override
public void onComplete() {
System.out.println( "onComplete");
}
});
3.zip操作符
把多个Observable合并后,并且把这些Observable的数据进行转换再发射出去。转换之后的数据数目由最短数据长度的那个Observable决定。发射完最终会自动调用观察者的onComplete方法()
Observable observable1 = Observable.just(1, 2, 3);
Observable observable2 = Observable.just("苹果", "香蕉", "橘子");
Observable observable3 = Observable.just(false,true);
Observable.zip(observable1, observable2, observable3, new Function3<Integer, String, Boolean, String>() {
@Override
public String apply(Integer integer, String s, Boolean aBoolean) throws Throwable {
return integer +s +aBoolean;
}
}). subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Object o) {
System.out.println( "onNext: "+ o.toString());
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
System.out.println( "onComplete");
}
});
4.combineLatest 操作符
当两个Observable 中的任何一个发送了数据,将先发送了数据的Observable的最新(最后)一个数据和另一个Observable发送的每个数据结合,最终基于该结合的结果发送数据,与zip()的区别: zip()是按个数合并,即1对1合并;而combineLatest()是基于时间合并,,即在同一时间点上合并
Observable.combineLatest(Observable.just(1, 2, 3),
Observable.intervalRange(3, 5, 2, 1, TimeUnit.SECONDS),
new BiFunction<Integer, Long, String>() {
@Override
public String apply(Integer integer, Long aLong) throws Throwable {
return "合并后的数据为:" + integer + aLong;
}
}).subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
Log.e("---->","combineLatest:"+ s);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
Log.e("---->","onComplete");
}
});
5.reduce操作符
把被观察者需要发送的数据按照指定规则聚合成一个数据发送
聚合的规则需要我们编写,内部流程是前两个数据按照我们的规则合并后,再与后面的数据按规则合并,依次类推(类使用数据累加 合并做运算,规则自己指定)。
Observable.just(1,2,3,4,5,6)
.reduce(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer integer, Integer integer2) throws Throwable {
return integer+integer2;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
6.collect操作符
作用是把 Observable(被观察者)发送的事件收集到一个数据结构中
Observable
.just(1, 2, 3, 4, 5).collect(new Supplier<ArrayList<Integer>>() {
@Override
public ArrayList<Integer> get() throws Throwable {
return new ArrayList<>();
}
}, new BiConsumer<ArrayList<Integer>, Integer>() {
@Override
public void accept(ArrayList<Integer> integers, Integer integer) throws Throwable {
integers.add(integer);
}
}).subscribe(new Consumer<ArrayList<Integer>>() {
@Override
public void accept(ArrayList<Integer> integers) throws Throwable {
Log.e("---->",""+integers);
}
});
7.startWith/startWithArray操作符
在一个被观察者发送时间前,追加发送一些数据/一个新的被观察者
Observable.just(1,2,3)
.startWithArray(5,6)
.startWith(Observable.just(1,2,3))
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
8.count(操作符
统计被观察者发送事件数量
Observable.just(1,2,3,4,5,9)
.count()
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Throwable {
System.out.println(aLong);
}
});
四、过滤操作符
1.filter操作符
指定过滤条件,过滤需要的事件/数据
Observable.just(1,2,3,4,5,6)
.filter(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Throwable {
return integer>4;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
2.ofType操作符
过滤指定类型的事件/数据
Observable.just("哈哈",2,3,4,5,"苹果")
.ofType(String.class)
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Throwable {
System.out.println(s);
}
});
3.skip操作符
过滤条件不满足的事件/数据
Observable.just("哈哈",2,3,"相机",7,5,"苹果")
.skip(4)
.subscribe(new Consumer<Serializable>() {
@Override
public void accept(Serializable serializable) throws Throwable {
System.out.println(serializable);
}
});
4.distinct/distinctUntilChanged操作符
过滤掉重复的事件/数据
distinc过滤全部重复的元素
Observable.just("哈哈",2,2,3,"相机",3,"相机",7,5,"苹果")
.distinct()
.subscribe(new Consumer<Serializable>() {
@Override
public void accept(Serializable serializable) throws Throwable {
System.out.println(serializable);
}
});
distinctUntilChanged只去除第一个重复的元素
Observable.just("哈哈",2,2,2,3,"相机",3,"相机",7,"苹果")
.distinctUntilChanged()
.subscribe(new Consumer<Serializable>() {
@Override
public void accept(Serializable serializable) throws Throwable {
System.out.println(serializable);
}
});
5.take操作符
按时间或者数量过滤事件/数据
Observable.just("哈哈",2,2,2,3,"相机",3,"相机",7,"苹果")
.take(4)
.subscribe(new Consumer<Serializable>() {
@Override
public void accept(Serializable serializable) throws Throwable {
System.out.println(serializable);
}
});
6.elementAt操作符
过滤指定位置的事件
Observable.just("哈哈",2,2,2,3,"相机",3,"相机",7,"苹果")
.elementAt(5)
.subscribe(new Consumer<Serializable>() {
@Override
public void accept(Serializable serializable) throws Throwable {
System.out.println(serializable);
}
});
7.throttleFirst/throttleLast操作符
按事件段过滤事件
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);//第一次发送
Thread.sleep(500);
emitter.onNext(2);//时间没有超过1s 不发送
Thread.sleep(500);
emitter.onNext(3); //时间为500+500 为1 s 发送
Thread.sleep(500);
emitter.onNext(4); //时间没有超过1s 不发送
Thread.sleep(1500);
emitter.onNext(5); //时间超过1 s 发送
Thread.sleep(500);
emitter.onNext(6);//时间没有超过1s 不发送
Thread.sleep(500);
emitter.onNext(7);//时间超过1 s 发送
}
})
.throttleFirst(1, TimeUnit.SECONDS)
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->" , ""+integer);
}
});
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);//第一不发送
Thread.sleep(500);
emitter.onNext(2);
Thread.sleep(500);
emitter.onNext(3);
Thread.sleep(500);
emitter.onNext(4);
Thread.sleep(1500);
emitter.onNext(5);
Thread.sleep(500);
emitter.onNext(6);
Thread.sleep(500);
emitter.onNext(7);
}
})
.throttleLast(1, TimeUnit.SECONDS)
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->" , ""+integer);
}
});
五、过滤操作符
1.all操作符
判断所有事件是否满足条件
Observable.just(2,2,2,3,3,7,6,85)
.all(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Throwable {
return integer>=2;
}
}).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Throwable {
System.out.println(aBoolean);
}
});
2.takeWhile
发送的事件判断条件不满足时,就会终止后续事件接收,所有数据必须满足条件才会执行,否则不执行
Observable.just(2,2,2,3,3,7,6,85)
.takeWhile(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Throwable {
return integer>=2;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
3.skipWhile
发送的事件判断条件不满足时,才接收后续的事件
Observable.just(2,2,2,3,3,7,6,85)
.skipWhile(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Throwable {
//相当于遍历每个元素去做判断
return integer>=4;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
4.takeUntil
过滤事件(同filter),发送complete的结束条件,当然发送结束之前也会包含这个值.
Observable.just(1,2,3,45,56,7)
.takeUntil(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) throws Throwable {
return integer==3;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
5.skipUntil
接收判断条件满足之外的事件,在观察者订阅原Observable时,该操作符将是忽略原Observable的发射的数据,直到第二个Observable发射了一项数据那一刻,它才 开始发射原Observable发射的数据。
Observable.just(1,2,3,45,56,7)
.skipUntil(Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
emitter.onNext("hahah");
System.out.println("我是先执行的");
}
})).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
6.sequenceEqual
判断2个被观察者发生的事件是否一样
Observable<Integer> just1 = Observable.just(1,2,3);
Observable<Integer> just2 = Observable.just(1,2,3,4);
Observable.sequenceEqual(just1,just2)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Throwable {
System.out.println(aBoolean);
}
});
7.contains
判断发送的数据里面是否包含指定数据
Observable.just(1,2,3,4,6,7)
.contains(2)
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Throwable {
System.out.println(aBoolean);
}
});
8.isEmpty
判断发送的数据是否为空
List<String> list = new ArrayList<>();
Observable.just(list)
.isEmpty()
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Throwable {
System.out.println(aBoolean);
}
});
9.amb
多个被观察者,只接收"第一个成功发送数据的被观察者",当需要发送多个Observable时,只接受先发送数据的Observerable 的数据 ,其余Observable会被丢弃
List<Observable<Integer>> list = new ArrayList<>();
Observable<Integer> just1 = Observable.just(1,2,3);
Observable<Integer> just2 = Observable.just(1,2,3,4);
list.add(just1);
list.add(just2);
Observable.amb(list)
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
六、其他操作符
1.常用的do系列操作符
1.doOnEach
注册一个动作,对Observable发射的每个数据项使用
Observable.just(1,2,3)
.doOnEach(new Consumer<Notification<Integer>>() {
@Override
public void accept(Notification<Integer> integerNotification) throws Throwable {
System.out.println("integerNotification:"+integerNotification.toString());
}
})
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println("onNext :"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
2.doOnSubscribe
注册一个动作,在观察者订阅时使用。内部由OperatorDoOnSubscribe实现
Observable.just(1,2,3)
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Throwable {
System.out.println("disposable:"+disposable.toString());
}
}) .subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println("onNext :"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
3.doOnNext
Observable.just(1,2,3)
.doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println("integer: "+integer);
}
}) .subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println("onNext :"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
4.doAfterNext
Observable.just(1,2,3)
.doAfterNext(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println("integer: "+integer);
}
}).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println("onNext :"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
5.doOnComplete
注册一个动作,对正常完成的Observable使用
Observable.just(1,2,3)
.doOnComplete(new Action() {
@Override
public void run() throws Throwable {
System.out.println("执行到我拉");
}
}).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println("onNext :"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
6.doOnErro
注册一个动作,对发生错误的Observable使用
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(121231);
int a = 0;
int b = 2/a;
}
}).doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Throwable {
System.out.println("执行到我拉 : "+throwable);
}
}).subscribe(new Observer<Serializable>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe : "+d);
}
@Override
public void onNext(@NonNull Serializable serializable) {
System.out.println("onNext :"+serializable);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError "+e);
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
2.错误/异常处理
1.onErrorRetuturn
抓捕异常并反馈特殊的结果&正常终止
如果出异常 打印100
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
int a = 0;
int b = 2/a;
emitter.onNext(3);
emitter.onNext(4);
emitter.onNext(5);
}
}).onErrorReturn(new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable throwable) throws Throwable {
return 100;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
2.onErrorResumeNext
抓捕异常并返回一个新的事件
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
int a = 0;
int b = 2/a;
emitter.onNext(3);
emitter.onNext(4);
emitter.onNext(5);
}
}).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends Integer>>() {
@Override
public ObservableSource<? extends Integer> apply(Throwable throwable) throws Throwable {
return Observable.just(11,22);
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
3.retry
异常重试:以下代码会无限打印1 2 ,会死循环
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
int a = 0;
int b = 2/a;
emitter.onNext(3);
emitter.onNext(4);
}
}).retry().subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
System.out.println(integer);
}
});
3.事件重发
1.repeat
repeat操作符就是对某一个Observable重复产生多次结果,当repeat() 接收到onComplete()会触发重订阅,默认情况下运行在一个新的线程上
Observable.range(0,2).repeat(2).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e("---->","Disposable:"+d);
}
@Override
public void onNext(@NonNull Integer integer) {
Log.e("---->","onNext:"+integer);
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("---->","onError:"+e.getMessage());
}
@Override
public void onComplete() {
Log.e("---->","onComplete:");
}
});
2.repeatWhen
就是可以让订阅者多次订阅,如:第一次订阅123 间隔3秒后又会重新订阅一次
Observable.just(1,2,3)
.repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(Observable<Object> objectObservable) throws Throwable {
return Observable.timer(3, TimeUnit.SECONDS);
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","integer:"+integer);
}
});
3.repeatUntil
设置重复,知道条件判断为止
Observable.just(1,2)
.repeatUntil(new BooleanSupplier() {
@Override
public boolean getAsBoolean() throws Throwable {
boolean b;
int rand = (int) (Math.random() * 10);
//如果随机产生的整数大于5,停止重复。
Log.e("---->","rand:"+rand);
if (rand > 5) {
b = true;
} else {
b = false;
}
return b;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","integer:"+integer);
}
});
4.delay
功能与timer操作符一样,但是delay用于在事件中,可以延迟发送事件中的某一次发送~
必须在安卓项目中执行:
Observable.just(1,2).delay(2, TimeUnit.SECONDS).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Throwable {
Log.e("---->","开始执行" +integer);
}
});
5.timeout
如果原始Observable过了指定的一段时长没有发射任何数据,就发射一个异常或者使用备用的Observable。
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
Thread.sleep(100);
emitter.onNext(3);
Thread.sleep(1000);
emitter.onNext(4);
emitter.onNext(5);
emitter.onComplete();
}
//如果不指定备用Observable将会抛出异常
}).timeout(999,TimeUnit.MICROSECONDS,Observable.just(99,100))
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e("---->","Disposable: "+d);
}
@Override
public void onNext(@NonNull Integer integer) {
Log.e("---->","integer: "+integer);
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("---->","Throwable: "+e.getMessage());
}
@Override
public void onComplete() {
Log.e("---->","onComplete: ");
}
});