-1

Having recently tried to learn RxJava, I wanted to replace my async tasks in Android in my viewmodel class with RxJava2. However when I run it, I get a "NetworkOnMainThreadException" exception when running the following:

 private void requestLocationDetails() {
    try {
        compositeDisposable.add(Observable
                .just(JsonRestCaller.readJsonFromUrl(buildUrl()))
                .subscribeOn(Schedulers.io())
                .subscribeWith(new DisposableObserver<JsonObject>() {
                    @Override
                    public void onNext(JsonObject jsonObject) {
                        try {
                            parseJson(jsonObject);
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                }));
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
}

As far as I have understood,

.subscribeOn(Schedulers.io())

causes my method to run on a background thread but Android states otherwise. Am I missing something here?

acoria
  • 90
  • 1
  • 1
  • 8

1 Answers1

0

First off, subscribeon just causes you to subscribe to the observable on another thread. Its observeOn that runs the onNext on another thread. Howerver I don't think that's your problem. Its that just is run on this thread. The just function is called immediately and emitted by the observable, so its called on the thread you call just on.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • @Onik Because I quickly realized the first one was wrong (it was correcting a mistake of his, but not the problem) and I didn't know the answer for sure so I deleted it. Turns out in a few minutes off research I was able to confirm my guess and reanswered. – Gabe Sechan Oct 19 '18 at 17:24
  • Ah, now I see, ok, that makes it a lot clearer. So what you are basically saying is that using just in combination with subscribeOn does not make any sense. – acoria Oct 19 '18 at 18:09