title: RxJava 2 / Retrofit 2 - NetworkOnMainThreadException
body: <p>I need to perform a request, if my token is expired I need to refresh it and retry the request.</p>
  
  <p>This is how I'm trying to do it, at the moment I can refresh the token but it throws me a NetworkOnMainThreadException. It finishes the request,update the token and reaches logs, but that exception its killing me. How can I avoid that?</p>
  
  <pre><code>    public Observable&lt;Estabelecimento&gt; listarEstabelecimentos() {
      return Observable.defer(this::getListarEstabelecimentoObservable)
              .retryWhen(throwableObservable -&gt; throwableObservable.flatMap(
                      throwable -&gt; {
                          if (throwable instanceof UnauthorizedException) {
                              return mRequestManager.getTokenObservable(AutoAtendimentoApplication.getContext())
                                      .doOnNext(response -&gt; /* log stuff */)
                                      .flatMap((Function&lt;AuthResponse, ObservableSource&lt;?&gt;&gt;) response2 -&gt;
                                              getListarEstabelecimentoObservable()
                                                      .doOnNext(estabelecimento -&gt;
                                                              /* log stuff */)
                                                      )
                                      );
                          }
                          return Observable.error(throwable);
                      }));
  }
  </code></pre>
  
  <p>NetWorkErrorHandler:</p>
  
  <pre><code>    public &lt;T&gt; T  processError(Response&lt;T&gt; response ) {
      switch (response.code()) {
          case 401:
              throw new UnauthorizedException();
          default:
              return response.body();
      }
  }
  </code></pre>
  
  <p>Token:</p>
  
  <pre><code>       private Observable&lt;AuthResponse&gt; getToken(Context context,
                                            @GrantType.GrantTypeDef String grantType, @Nullable String refreshToken) {
  
      SessionManager sessionManager = SessionManager.getInstance(context);
      Usuario usuario = sessionManager.getUser();
  
      AuthRequest request = new AuthRequest(usuario.getUsername(),
              usuario.getPassword(), grantType, refreshToken);
  
      return mAuthAPIService.getToken(request)
              .observeOn(AndroidSchedulers.mainThread())
              .subscribeOn(Schedulers.io())
              .map(response -&gt; storeTokens(response, context));
  }
  </code></pre>
  
  <p>Edit 1: I'm pretty sure the problem happens inside the flatmap and put subscribeOn does not solve the problem</p>
  
  <p>Edit 2: Code update</p>