1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android Architecture Componentsメモ

Posted at

Room

データの変更があっても、通知されない(Room + Dagger2)

以下のようにDaoでデータを取得するメソッドの戻り値をLiveDataにすると、その後データに変更があった場合に通知してくれる。

MailDao.kt
@Dao
interface MailDao {

    @Query("SELECT * FROM mail")
    fun loadMail(): LiveData<List<Mail>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertMails(mails: List<Mail>)

    @Query("DELETE FROM mail")
    fun clearTable()
}
MailViewModel.kt
var mailList: LiveData<List<Mail>> = mailDao.loadMails()
InboxFragment.kt
mailViewModel.mailList.observe(this, Observer { mailList ->
            if (mailList == null) {
                return@Observer
            }

            adapter?.setMailList(mailList.toMutableList())
        })

しかし、データの追加・変更をしても通知が来ない。
原因はDaggerでインスタンスを生成するときにシングルトンにしてなかったから。
@Singletonを追加して無事変更の通知が来ました。

AppModule.kt
    @Singleton  // ★追加
    @Provides
    fun provideMailDatabase(app: Application): MailDatabase = Room.databaseBuilder(app, MailDatabase::class.java, "mail").allowMainThreadQueries().build()

    @Singleton  // ★追加
    @Provides
    fun provideMailDao(database: MailDatabase) = database.mailDao()

参考:Room - LiveData observer does not trigger when database is updated

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?