Observables with SQLiteOpenHelper

Lets look at some code on how to use Observables with SQLiteOpenHelper.

I suppose you know how to work with SQLite in Android. Otherwise, take a look at http://developer.android.com/training/basics/data-storage/databases.html

So lets assume we got this class Database with whatever needed to create any tables needed.

The code below shows how to make a query and an insert. As you can see the query and insert is just like always, the only different is the creation of an observable and notification to the subscriber when query/insert is done.

So those methods can then be used asynchronous and the subscription is notified when done. The subscribeOn is taking a scheduler where the above methods will be executed, and observeOn where the subscription is executed (the code in .subscribe). AndroidSchedulers.mainThread() must be used if updating the UI.

Now I will show you a pretty neat feature that I often use when chaining observables, the flatMap. The code below writes the name to the database, the returned id is then passed to the get-method.

So that’s a way of using observables with Android and SQLlite.

Dependencies used:
me.tatarka:gradle-retrolambda:3.2.3
io.reactivex:rxandroid:1.1.0