1

I am following this codelab and one of the suggested best practices for retrieving data from a database was to use a LiveData wrapper for my DAO return values (step 6 in the codelab).

But in my app, I am reading an existing .sqlite file only once at the start of the activity. Thus using this wrapper should be unnecessary, am I correct?

So is it acceptable (in terms of best practices) to make my DAO return a simple object instead of using the LiveData construct around it?

Big_Chair
  • 2,781
  • 3
  • 31
  • 58

1 Answers1

1

There are two features of LiveData: delivery of updates and asynchronous operation.

If you will not be changing the data during the run of your app, you will not take advantage of the update-delivery feature of LiveData.

However, you still need to arrange to load the data on a background thread. If you plan on doing that by some other means (e.g., RxJava, your own background thread), you could avoid using LiveData.

Also, if your plan is to load all of the data in the database at the outset and never change it, then SQLite and Room are pointless. Just use a JSON file. The value in SQLite is in being able to query and modify parts of the data.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Two points: **1)** You are correct with that last point, however I have two activities using two different tables in the db. So the other one does use insert and delete operations. **2)** As to the other point, it's true, I still need the data loading on a background thread. What would be the correct way of doing it only once? I thought of simply triggering the observer manually, but the suggested answer for that [here](https://stackoverflow.com/a/51073400/1972372) is not very good looking. Any resource or link to an explanation would help. – Big_Chair Apr 22 '19 at 13:32
  • The problem was that I assumed the `onChanged` method of the observer did not fire initially. Further testing revealed that it was an IO issue with the file. So my question about doing it once became obsolete, as I can simply do that in this method. I guess I can consider my initial question answered by this though. – Big_Chair Apr 22 '19 at 18:18
  • 1
    @Big_Chair: "What would be the correct way of doing it only once?" -- if you are using RxJava, have your DAO return a `Single`. If you are using Kotlin coroutines, you may be able to have your DAO query function be a `suspend fun`. Otherwise, have the DAO just return the data, and do something else to call that DAO method on a background thread. Or, just use `LiveData`, which I am guessing is what you settled on. – CommonsWare Apr 22 '19 at 20:01