title: Observable with optional subscribers execute once
body: <p>How can an <code>Observer</code> have its logic execute once (asynchronously) regardless of subscribers.  My use-case is a <code>Provider</code> class that does CRUD for a <code>Model</code> class by delegating to another object (<code>SqliteOpenHelper</code>). A call to <code>ModelProvider.update</code> should persist changes to the model, whether the UI subscribes or not.</p>
  
  <pre><code>class ModelProvider {
      Observable&lt;String&gt; updateModel(Model model) {
          return Observable.create((Subscriber&lt;? super String&gt; subscriber) -&gt; {
              // synchronous for now, probably irrelevant
              String modelId = repository.save(model);
              subscriber.onNext(modelId);
          }).subscribeOn(Schedulers.io());
      }
  }
  
  class SomeActivity {
      void updateModel(Model model) {
          // dont care about the result, but need it to execute exactly once
          mModelProvider.updateModel(model);
      }
  }
  </code></pre>
  
  <p>I'm in the middle of moving a codebase to using RxJava and reactive patterns so the call to <code>repository.save(model)</code> is synchronous, but will still need the logic to execute exactly once afterwards, with or without UI subscribers.</p>
  
  <p>I've considered simply moving the repository logic out of the observable and then returning a different observable that uses the result of that:</p>
  
  <pre><code>class ModelProvider {
      Observable&lt;String&gt; updateModel(Model model) {
          String modelId = repository.save(model);
  
          return Observable.create((Subscriber&lt;? super String&gt; subscriber) -&gt; {
              subscriber.onNext(modelId);
          }).subscribeOn(Schedulers.io());
      }
  }
  </code></pre>
  
  <p>but this forces the IO work on the main thread and blocks it.</p>
  
  <p>another non-solution here:</p>
  
  <pre><code>    Observable&lt;String&gt; updateModel(Model model) {
          Observable&lt;String&gt; obs = Observable.create((Subscriber&lt;? super String&gt; subscriber) -&gt; {
          String modelId = repository.save(model);
              subscriber.onNext(modelId);
          }).subscribeOn(Schedulers.io());
  
          obs.subscribe();
  
          return obs;
      }
  </code></pre>
  
  <p>this does execute once at <code>obs.subscribe()</code> but executes again if the UI subscribes to it.</p>
  
  <p>I'm just now learning reactive patterns but I assume this is where <code>Subjects</code>/<code>Relays</code> are useful.</p>