title: Periodic HTTP Requests Using RxJava and Retrofit
body: <p>Is it possible to use RxJava/RxAndroid and Retrofit to perform periodic http requests to update data every x seconds? </p>
  
  <p>Currently I am using an IntentService and Recursive Handler/Runnable that fires every x seconds. I'd like to know if I could remove all that and let RxJava handle the requests instead.</p>
  
  <pre><code>final RestClient client = new RestClient();
  final ApiService service = client.getApiService();
  
  public interface ApiService {
      @GET("/athletes")
      public Observable&lt;List&lt;Athlete&gt;&gt; getAthletes();
  }
  
  service.getAthletes()
  .retry(3)
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Action1&lt;List&lt;Athlete&gt;&gt;() {
      @Override
      public void call(List&lt;Athlete&gt; athletes) {
          // Handle Success
      }
  }, new Action1&lt;Throwable&gt;() {
      @Override
      public void call(Throwable throwable) {
          // Handle Error
      }
  });
  </code></pre>
  
  <p><strong>EDIT</strong> </p>
  
  <p>After all is done I ended up with the following code. Any updates are welcome.</p>
  
  <pre><code>final Scheduler scheduler = Schedulers.from(Executors.newSingleThreadExecutor());
  
  obs = Observable.interval(30, TimeUnit.SECONDS, scheduler)
              .flatMap(tick -&gt; service.getAthletes(1, 0l))
              // Performed on service.getAthletes() observable
              .subscribeOn(scheduler)
              .observeOn(AndroidSchedulers.mainThread())
              .doOnError(err -&gt; Log.d("APP", "Error retrieving athletes: " + err.toString()))
              .retry()
              .flatMap(Observable::from)
              .filter(athlete -&gt; {
                  // Process Athlete here in the filter
                  // Return true to always send messages but could filter them out too
                  return true;
              });
  
  public static void startUpdates() {
      if (sub != null) {
          sub = obs.subscribe(athlete -&gt; {
              Log.d("APP", "Done updating athletes! ");
          });
      }
  }
  
  public static void stopUpdates() {
      sub.unsubscribe();
      sub = null;
  }
  </code></pre>