In RxJava, is subscribeOn(mainThread).subscribe() guaranteed to run synchronously in mainThread? Or is it possible that another piece of work already scheduled to run on the main thread may run first?
e.g.
printA.subscribeOn(mainThread).subscribe() // called from a background thread at t=1 second
....
System.out.println("B"); // called from main thread at t=2
printC.subscribeOn(mainThread).subscribe() // called from main thread at t=3
System.out.println("D"); // called from main thread at t=4
Would the below be a possible outcome?
B
D
A
C
Would this depend on the scheduler implementation? For example, this is on Android with main thread scheduler.
The subscribeOn(mainThread).subscribe() will put the task at the end of the main thread's looper so whenever the main thread is free, it will get processed. It does not run immediately even if called from the mainThread itself.
Two scenarios are possible:
1. main thread is busy until the print of D
In this case, the result will be B-D-A-C.
2. main thread is free until the print of B
In this case, the result will be A-B-D-C