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

后端 未结 3 1951
一向
一向 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 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? {
            return GetChildDiscussionAsyncTask(discussionDao).execute(parentId).get()
        }
    
    private class GetChildDiscussionAsyncTask constructor(private val discussionDao: DiscussionDao?): AsyncTask?>() {
            override fun doInBackground(vararg params: Int?): List? {
                return discussionDao?.getChildDiscussionList(params[0]!!)
            }
        }
    

    Dao Class

    @Query("SELECT * FROM discussion_table WHERE parent_id = :parentId")
    fun getChildDiscussionList(parentId: Int): List?
    

提交回复
热议问题