title: SQLite transaction and RxJava
body: <p>There is how I save my data with RxJava:</p>
  
  <pre><code>override fun put(note: Note): Observable&lt;Note&gt; {
      validateNote(note)
      return Observable.just(note)
              .doOnNext { dbKeeper.startTransaction() }
              .doOnNext { storeHashtags(note) }
              .doOnNext { storeImages(note) }
              .flatMap { notesDataStore.put(notesMapper.transform(note)) }
              .map { notesMapper.transform(it) }
              .doOnNext { dbKeeper.setTransactionSuccessful() }
              .doOnUnsubscribe { dbKeeper.endTransaction() }
  }
  </code></pre>
  
  <p>And then I use this method like this:</p>
  
  <pre><code>      notesManager.put(note)
              .switchMap { notesManager.getHashtags() }
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe {view.setHashtags(it) }
  </code></pre>
  
  <p>And <code>doOnUnsubscribe</code> never called as <code>getHashtags()</code> trying to SELECT from db that locked by <code>startTransaction()</code>. Deadlock, heh.
  Okay. Let's replace <code>doOnUnsubscribe(...)</code> with <code>doOnTerminate(...)</code>.</p>
  
  <pre><code>override fun put(note: Note): Observable&lt;Note&gt; {
      validateNote(note)
      return Observable.just(note)
              .doOnNext { dbKeeper.startTransaction() }
              .doOnNext { storeHashtags(note) }
              .doOnNext { storeImages(note) }
              .map { notesMapper.transform(note) }
              .flatMap { notesDataStore.put(it) }
              .map { notesMapper.transform(it) }
              .doOnNext { dbKeeper.setTransactionSuccessful() }
              .doOnTerminate { dbKeeper.endTransaction() }
  }
  </code></pre>
  
  <p>But now transaction won't close if <code>Observable</code> will be interrupted by <code>subscriber.unsubscribe()</code>. </p>
  
  <p>What can you recommend to solve my situation?</p>
  
  <p>Additional information:
  I use one writableDb instance to write/read data.</p>