2

I'm writing a message to my Room db to then send it to the server when this is succesful I update the message in the database.

When I try this from a Worker (WorkManager) the LiveData that holds the messages doesnt update even tho the message gets written to the db.

Small example (insert doesnt update LiveData but when I restart the app the message shows up):

override fun doWork(): Result {
    appDatabase = appDatabase(applicationContext)
    val messageId = inputData.getString("messageId", "") ?: ""

    val message = appDatabase.messageDao().getMessage(messageId)
    appDatabase.messageDao().insertMessage(Message(message.conversationId, "XYZ 234234234234", "test", "test", SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.GERMANY).format(Date()), false))

    return Result.SUCCESS
}

Outside of the Worker everything works fine.

TeKo
  • 465
  • 1
  • 5
  • 17

2 Answers2

4
Room.databaseBuilder(application, Database::class.java,"dbname")
            .allowMainThreadQueries()
            .enableMultiInstanceInvalidation() // maybe room database create multi instance. add this line solved my problem
            .fallbackToDestructiveMigration()
            .build()

the problem was room database instance created more than once. just try add this line. all room database instance have created can be tracked and invalidate data source if there are modifications.

.enableMultiInstanceInvalidation() 

another solution, i use dagger (dependency injection) and add @Singleton annotation at provide function the room database instance. to prevent room database instance created more than once.

0

Not exactly sure what the problem was, but its working now.

Im injecting everything (db and services) into my worker now, maybe that helped (Not sure if it makes a difference if I use the same instance of my db).

TeKo
  • 465
  • 1
  • 5
  • 17
  • I have the same exact problem. Here is the link to it. ( https://stackoverflow.com/questions/60589304/insert-on-room-db-does-not-trigger-observer-on-activity ). Is there a way that you can help me in case you have found the solution? Thnx – james04 Mar 09 '20 at 15:10