Search code examples
androidkotlinandroid-roomandroid-livedata

LiveData not updating from insert in Room


I want to propagate repository response to the user as a toast so i put live data listener in my activity on post create method

mainViewModel.toast.observe(this) {
            Log.d(TAG, "initViews: $it")
            if (it.notPropagated) {
                Toast.makeText(
                    this,
                    it.message,
                    if (!it.longToast) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
                ).show()
                mainViewModel.setMessageToPropagated()
            }
        }

toast is simple live data created from flow i get from database

val toast = mainRepository.getMessage().asLiveData(viewModelWorkerContext)

but when I'm trying to change the data in database in other fragment by using insert it never actually update on change, only when I restart application it is getting the stuff from database and respond to the mainViewModel.setMessageToPropagated() that changes message to "used" and that triggers livedata no problem. Here is my DAO:

@Dao
interface RoomDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun setMessage(message: SingleTimeUserMessage)

    @Query("SELECT * FROM SingleTimeUserMessage WHERE notPropagated = true LIMIT 1")
    fun getMessageToPropagate(): Flow<SingleTimeUserMessage>

    @Query("SELECT * FROM SingleTimeUserMessage LIMIT 1")
    fun getMessageToPropagated(): SingleTimeUserMessage
}

And lastly, providers

@Module
@InstallIn(SingletonComponent::class)
object RoomDatabase {
    @Provides
    @Singleton
    fun provideMainDatabase(app: Application): MainDatabase =
        Room.databaseBuilder(app, MainDatabase::class.java, "MainDatabase")
            .fallbackToDestructiveMigration()
            .build()

    @Singleton
    @Provides
    fun provideTvDao(database: MainDatabase): RoomDao {
        return database.tvDao()
    }
}

I read many topics related to this problem and it was often resolved by making providers return the same instance of database but as far as I know my providers should always return the same instance. Any ideas and help would be appreciated.


Solution

  • There was an error in my code that I was not aware works like that. I had useless annotations on all my Repositories

    @Module
    @InstallIn(ActivityRetainedComponent::class)
    

    after removing it everything seems to run great.

    Hope this can help someone in future that struggles with similar problems.