问题
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?
回答1:
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
- Kotlin Coroutines. https://developer.android.com/codelabs/kotlin-android-training-coroutines-and-room#0
- RxJava(RxAndroid) https://medium.com/androiddevelopers/room-rxjava-acb0cd4f3757
- LiveData https://developer.android.com/codelabs/android-training-livedata-viewmodel#0
- Executors
- 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.
来源:https://stackoverflow.com/questions/65642957/what-is-the-best-way-to-not-use-allowmainthreadqueries-using-android-room