Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJava Observable executing on main thread instead of background thread

I created an Observable using the Observable.fromCallable method and subscribed to it as shown in the code snippet below.

Observable<String> stringObservable = Observable.fromCallable(new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            return Thread.currentThread().getName();
        }
});

stringObservable.subscribeOn(Schedulers.io());
stringObservable.observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String aDouble) {
                Toast.makeText(SimpleActivity.this, "onNext: " + aDouble, 
                Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(SimpleActivity.this)
                        .setTitle("Error")
                        .setMessage(e.toString())
                        .show();
            }

            @Override
            public void onComplete() {

            }
        });

The snippet above produced a toast showing that the Callable was run on the main thread instead of the Schedulers.io thread. What's happening?

like image 287
Edwin Nyawoli Avatar asked Mar 07 '23 09:03

Edwin Nyawoli


1 Answers

Every operation on an Observable creates a new instance and does not effect the original one. Therefore

stringObservable.subscribeOn(Schedulers.io());

does not affect your code below.

The correct way of using them would be in a chain instead of using a variable.

Observable.fromCallable(new Callable<String>() {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return Thread.currentThread().getName();
    }
}).subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String aDouble) {
            Toast.makeText(SimpleActivity.this, "onNext: " + aDouble, 
            Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(Throwable e) {
            new AlertDialog.Builder(SimpleActivity.this)
                    .setTitle("Error")
                    .setMessage(e.toString())
                    .show();
        }

        @Override
        public void onComplete() {

        }
    });
like image 129
Tim Freiheit Avatar answered Apr 25 '23 12:04

Tim Freiheit