strada android
strada android

Reputation: 39

RxJava NetworkOnMainThreadException despite correctly calling observeOn(io thread)

Here is the code

        getCompositeDisposable().add(Single.fromCallable(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    URL url = new URL(pageUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    int code = connection.getResponseCode(); // <- crashes here
                    return code == 200;
                }
            })
                    .observeOn(getSchedulerProvider().io())
                    .subscribeOn(getSchedulerProvider().ui())
                    .subscribe((pageAvailable) -> {
                        boolean useCache = !pageAvailable;
                        getMvpView().loadPage(useCache, pageUrl);
                    }, Timber::e)
    );

Cant understand what is the problem here. The network code should be run on io thread and then return result to ui thread. Does this code even runs on io thread? Im confused.

Upvotes: 0

Views: 62

Answers (1)

a_local_nobody
a_local_nobody

Reputation: 8191

despite correctly calling observeOn(io thread)

Incorrect, your code should be:

  .subscribeOn(getSchedulerProvider().io()) //do work on the io thread
  .observeOn(getSchedulerProvider().ui()) //apply changes to ui thread

always remember that subscribeOn is where you'll be doing the work and order does matter

Upvotes: 4

Related Questions