Here is my code:
package com.example.myapplication;
import io.reactivex.Observable;
public class SampleRx {
Observable<String> getBoth() {
return Observable.merge(getSeq1(), getSeq2());
}
Observable<String> getSeq1() {
return Observable.create(emitter -> {
emitter.onNext("A");
Thread.sleep(1_500);
emitter.onNext("B");
Thread.sleep(500);
emitter.onNext("C");
Thread.sleep(250);
emitter.onNext("D");
Thread.sleep(2_000);
emitter.onNext("E");
// Thread.sleep(2_000);
emitter.onComplete();
});
}
Observable<String> getSeq2() {
return Observable.create(emitter -> {
Thread.sleep(200);
emitter.onNext("1");
Thread.sleep(500);
emitter.onNext("2");
Thread.sleep(400);
emitter.onNext("3");
Thread.sleep(300);
emitter.onNext("4");
Thread.sleep(1_800);
emitter.onNext("5");
emitter.onComplete();
});
}
}
Here is the output:
val=A
val=D
val=4
val=5
Why is there 5
whereas E
is ignored (because it's followed by onComplete()
as I guess).
Running your code :
SampleRx().getBoth().subscribe(System.out::println);
I get :
A
B
C
D
E
1
2
3
4
5
This is correct behaviour, results will not be interleaved as this uses the calling/same thread for all emissions, and the merge
only completes when both Obervables signal completed.
To achieve interleaving for the merge each Observable
need to run on a different thread, so they do not block one another, so if each observable is subscribed to on io
ie
Observable.<String>create(emitter -> {
emitter.onNext(value);
...
...
emitter.onComplete();
}).subscribeOn(Schedulers.io());
Then you get this output :
A, Thread : RxCachedThreadScheduler-1
1, Thread : RxCachedThreadScheduler-2
2, Thread : RxCachedThreadScheduler-2
3, Thread : RxCachedThreadScheduler-2
4, Thread : RxCachedThreadScheduler-2
B, Thread : RxCachedThreadScheduler-1
C, Thread : RxCachedThreadScheduler-1
D, Thread : RxCachedThreadScheduler-1
5, Thread : RxCachedThreadScheduler-2
E, Thread : RxCachedThreadScheduler-1
Which then honours independent emissions that do not block each other.
You have not provided any information regarding a debounce, which you included in your title, so I cannot comment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.