Closed
Description
I have a resource which I want to release upon unsubscribing of the Observable, and release action must be run on the same thread which I created the resource.
So I found Observable.using
and assumed that resourceFactory & disposeAction will run on a same thread which I specified with subscribeOn
.
At first it seems working as I expected, but I realized that sometimes disposeAction runs on different thread than I specified with subscribeOn
public class UsingResourceSample {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Observable.using(() -> {
String factoryThread = "Getting @" + Thread.currentThread().toString();
System.out.println(factoryThread);
return factoryThread;
},
Observable::just,
(factoryThread) -> System.out.println("Closing @" + Thread.currentThread().toString() + ", " + factoryThread))
.subscribeOn(Schedulers.io())
.subscribe()
.unsubscribe();
}
}
}
If I run this code multiple times, most of the time it shows Closing @ThreadA, Getting @ThreadA
, but sometimes it shows Closing @ThreadB, Getting @ThreadA
.
So, here are questions:
- is this behavior intentional?
- is there any way to run resourceFactory & disposeAction to run on the same thread which I specified with
subscribeOn
?