Skip to content

Question about Observable.using's resourceFactory & disposeAction #4197

Closed
@yshrsmz

Description

@yshrsmz

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:

  1. is this behavior intentional?
  2. is there any way to run resourceFactory & disposeAction to run on the same thread which I specified with subscribeOn?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions