Android -room persistent library - DAO calls are async, therefore how to get callback?

后端 未结 3 1949
一向
一向 2021-02-05 05:29

From what i have read Room doesn’t allow you to issue database queries on the main thread (as can cause delays on the main thread)). so imagine i am trying to

相关标签:
3条回答
  • 2021-02-05 05:58

    There is a way to turn off async and allow synchronous access.

    when building the database you can use :allowMainThreadQueries()

    and for in memory use: Room.inMemoryDatabaseBuilder()

    Although its not recommended. So in the end i can use a in memory database and main thread access if i wanted super fast access. i guess it depends how big my data is and in this case is very small.

    but if you did want to use a callback.... using rxJava here is one i made for a list of countries i wanted to store in a database:

    public Observable<CountryModel> queryCountryInfoFor(final String isoCode) {
        return Observable.fromCallable(new Callable<CountryModel>() {
            @Override
            public CountryModel call() throws Exception {
                return db.countriesDao().getCountry(isoCode);
            }
        }).subscribeOn(Schedulers.io())
           
     .observeOn(AndroidSchedulers.mainThread());
    

    }

    you can then easily add a subscriber to this function to get the callback with Rxjava.

    0 讨论(0)
  • 2021-02-05 06:09

    As Bohsen suggested use livedata for query synchronously. But in some special case, we want to do some asynchronous operation based on logic. In below example case, I need to fetch some child comments for the parent comments. It is already available in DB, but need to fetch based on its parent_id in recyclerview adapter. To do this I used return concept of AsyncTask to get back the result. (Return in Kotlin)

    Repositor Class

    fun getChildDiscussions(parentId: Int): List<DiscussionEntity>? {
            return GetChildDiscussionAsyncTask(discussionDao).execute(parentId).get()
        }
    
    private class GetChildDiscussionAsyncTask constructor(private val discussionDao: DiscussionDao?): AsyncTask<Int, Void, List<DiscussionEntity>?>() {
            override fun doInBackground(vararg params: Int?): List<DiscussionEntity>? {
                return discussionDao?.getChildDiscussionList(params[0]!!)
            }
        }
    

    Dao Class

    @Query("SELECT * FROM discussion_table WHERE parent_id = :parentId")
    fun getChildDiscussionList(parentId: Int): List<DiscussionEntity>?
    
    0 讨论(0)
  • 2021-02-05 06:13

    If you want to do your query synchronously and not receive notifications of updates on the dataset, just don't wrap you return value in a LiveData object. Check out the sample code from Google.

    Take a look at loadProductSync() here

    0 讨论(0)
提交回复
热议问题