Skip to content
Advertisement

What is the best way to not use allowmainthreadqueries() using Android Room?

I always use allowmainthreadqueries() in Android Room. But many people say it is not recommend to do it. With this function, Room is very easy to use. But if i should change my app to not using this function, How do I do that? Is there an effective way to do it?

Advertisement

Answer

Yes, It is not a good approach to query DB on Main Thread. There are different ways, to keep the DB operation off the main(UI) thread, Mainly

  1. Kotlin Coroutines. https://developer.android.com/codelabs/kotlin-android-training-coroutines-and-room#0
  2. RxJava(RxAndroid) https://medium.com/androiddevelopers/room-rxjava-acb0cd4f3757
  3. LiveData https://developer.android.com/codelabs/android-training-livedata-viewmodel#0
  4. Executors
  5. AsycTask

Out of the above, the best option would always depend upon what is your use case. But the first three are the best options to use. since they provide a callback on the result of a query.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement