Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjava: Subscribe on the specific thread

I'm a newbie in Rxjava. I have the following code:

    System.out.println("1: " + Thread.currentThread().getId());
    Observable.create(new rx.Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subcriber) {
            System.out.println("2: " + Thread.currentThread().getId());
            // query database
            String result = ....
            subcriber.onNext(result);
        }

    }).subscribeOn(Schedulers.newThread()).subscribe(countResult -> {
        System.out.println("3: " + Thread.currentThread().getId());
    });

For example, the output will be:

1: 50
2: 100
3: 100

I want subscribers run on the thread that has id 50. How can I do that?

like image 887
Meo Beo Avatar asked Nov 26 '22 15:11

Meo Beo


1 Answers

I think that there are two cases. Either you need it to run on the UI thread, or because of synchronisation. As I know you can not call a function on a specific thread, because when the method is called it is bound to the context of the thread, so it is impossible to call a method from a thread to another thread. Your problem is that the method in subscriber is called from Schedulers.newThread(). I also found this github issue about Schedulers.currentThread(). What you need is to notify the caller thread when the observer gets called.

Also you can use akka, it is way simpler to write concurrent code with it.

Sorry for my bad grammar.

like image 143
alex4o Avatar answered Dec 04 '22 15:12

alex4o