Skip to content Skip to sidebar Skip to footer

How To Use Room And Databases Without Livedata In Android?

I am new to room and I wanna set up a database for my app. I walked through the documentary for room on developer.android.com. I wrote a little app which uses LiveData and it works

Solution 1:

How can I retrieve data from my database without using the LiveData concept?

Don't use LiveData as a return type from your DAO methods.

As far as I know queries shouldn't be on the main-thread. So I would have to put it in an asyncTask

It would be much better for you to use LiveData, Kotlin coroutines, or RxJava than AsyncTask. Even a plain Thread or single-thread Executor would be better, given that this code seems to be in a repository and not tied to the UI.

In particular, any time you use AsyncTask with only doInBackground(), there was no need to use AsyncTask in the first place, compared to a simple thread. The only reason to use AsyncTask is because you need onPostExecute() to do some work on the main application thread.

And, since AsyncTask is considered to be obsolete, I really encourage you to use something else. Room has built-in support for LiveData, Kotlin coroutines, and RxJava.

If I fire two or more queries at the same time I need a mechanism to ensure that all asyncTasks have finished like a onFinishedAllLoadingListener. What is the best way to do this?

In your case, just put them in a single thread. Your code will not have two or more queries at the same time anyway, as AsyncTask uses a single background thread by default.

In terms of other likely solutions:

  • With Kotlin coroutines, probably async() and await() are the simplest options

  • With RxJava, as EpicPandaForce suggested, use the zip() operator

  • With LiveData, use a library that offers a zip() operator, or create your own

Post a Comment for "How To Use Room And Databases Without Livedata In Android?"