RxJava 转换操作符 switchMap

时间:2021-01-27 17:48:36

switchMap与flatMap和concatMap的区别在于:不好总结:

RxJava also implements the switchMap operator. It behaves much like flatMap, except that whenever a new item is emitted by the source Observable, it will unsubscribe to and stop mirroring the Observable that was generated from the previously-emitted item, and begin only mirroring the current one.


switch()和flatMap()很像,除了一点:当源Observable发射一个新的数据项时,如果旧数据项订阅还未完成,就取消旧订阅数据和停止监视那个数据项产生的Observable,开始监视新的数据项.


看例子:

<pre name="code" class="java"> Observable.just("A", "B", "C", "D", "E").switchMap(new Func1<String, Observable<String>>() {
@Override
public Observable<String> call(String s) {
Observable<String> ob = Observable.just(s);
return ob;
}
}).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
@Override
public void onCompleted() {
LogUtils.d("------>onCompleted()");
}

@Override
public void onError(Throwable e) {
LogUtils.d("------>onError()" + e);
}

@Override
public void onNext(String s) {
LogUtils.d("------>onNext:" + s);
}
});

结果:

 
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onNext:A
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onNext:B
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onNext:C
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onNext:D
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onNext:E
02-26 17:10:28.878 28598-28598/com.rxandroid.test1 D/----->: ------>onCompleted()
 
这是在同一线程产生数据,所以当第二个数据项来临时,第一个已经完成了,同理,c,d,e都将完成
 
下面来看并发产生数据项:
<pre name="code" class="java"> Observable.just("A", "B", "C", "D", "E").switchMap(new Func1<String, Observable<String>>() {            @Override            public Observable<String> call(String s) {                return Observable.just(s).subscribeOn(Schedulers.newThread());            }        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {            @Override            public void onCompleted() {                LogUtils.d("------>onCompleted()");            }            @Override            public void onError(Throwable e) {                LogUtils.d("------>onError()" + e);            }            @Override            public void onNext(String s) {                LogUtils.d("------>onNext:" + s);            }        });

结果:
 
02-26 17:19:17.138 4980-4980/com.rxandroid.test1 D/----->: ------>onNext:E
02-26 17:19:17.138 4980-4980/com.rxandroid.test1 D/----->: ------>onCompleted()
当源Observable变换出的Observable同时进行时,
A --> 取消空的,没有可以取消的
B--> A被取消
C-->  B被取消
D-->  C被取消
E-->  D被取消