Android Room: Synchronous queries return null

Viewed 5833

I have a Site and corresponding SiteDao:

@Dao
interface SiteDao {
    @get:Query("SELECT * FROM site WHERE uid = 1 LIMIT 1")
    val site: LiveData<Site>

    @get:Query("SELECT * FROM site WHERE uid = 1 LIMIT 1")
    val getSiteSync: Site

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(context: Site)
}

This works:

siteRepository.getSite().observe(activity, Observer<Site> {
     // `it` is instance of Site, working as intended
})

This doesn't:

Thread {
    val site = siteRepository.getSiteSync()
    // site is null
}.start()

Nevermind that I'm using Repository instead of ViewModel, just an example.

Any idea why?

1 Answers

Room doesnt allow synchronous queries by default.

To achieve that you have to explicity call allowMainThreadQueries while initializing your database.

That is designed that way because database selection should observe for changes and ain't fetched immediately.

Related