Android LiveData Observer alternative with respect to performance

Viewed 1250

I am currently developing an app that among other things is able to record the smartphones sensors like acceleration etc. and plot them with the help of the GraphView library. At the moment im reading the sensors value into a Room SQLite database and then by using an observer that observes the table with the help of a LiveData object im getting the new measurements and add the last new measurement to series in the Graph. This is how I update the Graph:

sharedViewModel.allAccelerations.observe(viewLifecycleOwner, Observer<List<MeasurementDatabaseHelper.Measurement>> { measurements ->
    if (sharedViewModel.isReset.value == true && measurements.isNotEmpty()) {
        val time = (measurements.last().time.toDouble() - measurements.first().time.toDouble())*1e-9
        val accX = measurements.last().accX.toDouble()
        series.appendData(DataPoint(time, accX), true, 50)

    }

My Problem is however that the Observer does not react to every added measurement, so that im skipping values when I add the last measurement to the series. I could surely write code that checks how many values have to be added every time the Observer reacts to a LiveData change, but that does not seem like a good option in terms of performance for me. Does anybody maybe have a better idea how to synchronize the measurements in the database with the GraphViews series?

1 Answers

LiveData is not a stream. It is meant to represent a self-sufficient state; it should not be used for a series of independent events that you build your state upon. When you use it as intended, you should not be worried about skipping states as you only care about the current state.

What you seem to be pursuing is a reactive stream. If you use Room, you may try RxJava and represent your measurement events as a Flowable stream. That would give you full control over backpressure (you can be explicit about whether you want to skip events, or buffer them, etc). Room has a built-in support for Rx-observable queries.

Another approach would be using LiveData that always gives a full dataset but I'm not sure if that would satisfy your constraints.

Related