title: How to manage Looper thread needed in RxJava
body: <p>I want to encapsulate in an <code>Observable</code> a logic that queries a <code>ContentProvider</code> and also subscribes <code>ContentProvider</code> cursor to supply continuous updates.</p>
  
  <p>As the observable does IO work I need to subscribe it in <code>Schedulers.io()</code>. The problem with that is that then I can't register a <code>ContentObserver</code> because it needs a looper prepared thread.</p>
  
  <p>What is the recommended way to manage that and <strong>encapsulate</strong> it in a single <code>Observable</code>.</p>
  
  <p>Code to illustrate that:</p>
  
  <pre><code>public Observable&lt;Integer&gt; unreadCountObservable() {
      return Observable.create(subscriber -&gt; {
          new UnreadCountObservable(subscriber);
      });
  }
  
  private class UnreadCountObservable {
      private Subscriber subscriber;
  
      public UnreadCountObservable(Subscriber subscriber) {
          this.subscriber = subscriber;
          Cursor cursor = queryUnread(subscriber);
          cursor.registerContentObserver(observer);
          subscriber.add(Subscriptions.create(() -&gt; {
              cursor.unregisterContentObserver(observer);
              cursor.close();
          }));
      }
  
      @NonNull
      private Cursor queryUnread(Subscriber subscriber) {
          Cursor cursor = contextProvider.getContext().getContentResolver().query(Uri.parse(CONTENT_URI),SMS_PROJECTION,SMS_SELECTION_UNREAD,SMS_PROJECTION,null);
          if(cursor.moveToNext()) {
              Integer count = cursor.getInt(0);
              subscriber.onNext(count);
          } else {
              subscriber.onNext(0);
          }
          return cursor;
      }
  
      private ContentObserver observer = new ContentObserver(new Handler()) {
          @Override
          public boolean deliverSelfNotifications() {
              return false;
          }
  
          @Override
          public void onChange(boolean selfChange) {
              Timber.d("New sms data changed");
              queryUnread(subscriber);
          }
      };
  }
  </code></pre>
  
  <p><strong>Note 1</strong> The problem with the above code is that it can't be called with <code>.subscribeOn(Schedulers.io()</code> due to the registerObserver, and if it's called it mainThread then the queries also run on them)</p>
  
  <p><strong>Note:</strong> Encapsulating all in a single <code>Observable</code> is a key requirement and the motive of this question</p>
  
  <p>My best idea now is to create a HandlerThread for activity where I use the Observable and use the looper from that thread. But want to know if there are better alternatives, and if making a generic scheduler (e.g looperIoScheduler()) makes sense on can cause problems.</p>