title: retrofit with rxjava handling network exceptions globally
body: <p>I am trying to handle exceptions in app on global level, so that retrofit throws an error i catch it in some specific class with logic for handling those errors. </p>
  
  <p>I have an interface</p>
  
  <pre><code>@POST("/token")
  AuthToken refreshToken(@Field("grant_type") String grantType, @Field("refresh_token") String refreshToken);
  </code></pre>
  
  <p>and observables </p>
  
  <pre><code>/**
   * Refreshes auth token
   *
   * @param refreshToken
   * @return
   */
  public Observable&lt;AuthToken&gt; refreshToken(String refreshToken) {
      return Observable.create((Subscriber&lt;? super AuthToken&gt; subscriber) -&gt; {
          try {
              subscriber.onNext(apiManager.refreshToken(REFRESH_TOKEN, refreshToken));
              subscriber.onCompleted();
          } catch (Exception e) {
              subscriber.onError(e);
          }
      }).subscribeOn(Schedulers.io());
  }
  </code></pre>
  
  <p>When i get 401 from server (invalid token or some other network related error) i want to refresh the token and repeat the rest call. Is there a way to do this with rxjava for all rest calls with some kind of observable that will catch this error globally, handle it and repeat the call that throw-ed it?</p>
  
  <p>For now i am using subject to catch the error on .subscribe() like this</p>
  
  <pre><code>private static BehaviorSubject errorEvent = BehaviorSubject.create();
  
  public static BehaviorSubject&lt;RetrofitError&gt; getErrorEvent() {
      return errorEvent;
  }
  </code></pre>
  
  <p>and in some call </p>
  
  <pre><code>getCurrentUser = userApi.getCurrentUser().observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                      (user) -&gt; {
                          this.user = user;
                      },
                      errorEvent::onNext
              );
  </code></pre>
  
  <p>then in my main activity i subscribe to that behaviour subject and parse the error </p>
  
  <pre><code>SomeApi.getErrorEvent().subscribe(
              (e) -&gt; {
                  //parse the error
              }
      );
  </code></pre>
  
  <p>but i cant repeat the call for the observable that throw the error.</p>