I am new to RxJava and I am trying to understand the following threading behavior:
public static void main(String[] args) throws Exception {
List<String> items = new ArrayList<>();
items.add("a");
items.add("b");
items.add("c");
items.add("d");
Observable<String> myObservable = Observable.fromIterable(items);
myObservable.
flatMap(s->Observable.just(s+1).subscribeOn(Schedulers.newThread())).
subscribe(s->{System.out.println(Thread.currentThread().getId() + " " + s);});
Thread.sleep(5000);
}
This output is printed:
16 d1
15 c1
14 b1
13 a1
Which implies that the Consumer is being called on a seperate thread for each item and the job is done concurrently.
When Thread.sleep is added to the end/start of the Consumer method e.g.
s->{System.out.println(Thread.currentThread().getId() + " " + s); Thread.sleep(1000);}
The output is:
15 c1
15 a1
15 b1
15 d1
The order of the items can be changed but the thread id is always the same, and it looks like the job is done sequentially.
I would expect it to behave the same way the first example
Can anyone exaplain this behaviour ?
Thanks a lot
Avi