ObjectBox: LiveData with Android Architecture Components

Since ObjectBox 1.2.0. Have a look at the example project on GitHub.

As an alternative to ObjectBox’ data observers and reactive queries, you can opt for the LiveData approach supplied by Android Architecture Components. ObjectBox comes with  ObjectBoxLiveData, a class that can be used inside your ViewModel classes.

A simple ViewModel implementation for our note example app includes the special ObjectBoxLiveData that is constructed using a regular ObjectBox query:

Note that we did choose to pass the box to getNoteLiveData() . Instead you could use  AndroidViewModel , which provides access to the Application  context, and then call  ((App) getApplication()).getBoxStore().boxFor()  inside the ViewModel. However, the first approach has the advantage that our ViewModel  has no reference to Android classes. This makes it easier to unit test.

Now, when creating the activity or fragment we get the ViewModel, access its LiveData and finally register to observe changes:

The ObjectBoxLiveData will now subscribe to the query and notify observers when the results of the query change, if there is at least one observer. In this example the activity is notified if a note is added or removed. If all observers are destroyed, the LiveData will cancel the subscription to the query.

If you have used ObjectBox observers in the past this might sound familiar. Well, because it is! ObjectBoxLiveData just wraps a DataObserver on the query you give to it.

Related Topics


Spread the love

Synchronization is coming   GET YOUR EARLY ACCESS