1

This is a bug I have "fixed" but I want to know why and what is going on.

Initially, I had a single room database instance, which is used to initialize a single repository instance. Both of these were used throughout the app as they were instantiated in the Application class of my app.

I had two viewModels, both of which accept that single repository instance as a parameter. The repository returned a Flow<> as a return type from one of the functions.

Hence, when one viewModel modifies the database, the other recieves that change since it recieved a Flow.

Now I wanted to move away from manual dependency injection and used Hilt.

Accidently I forgot to switch one of the viewModels to use the Hilt provideed instance of the repository.

Suddenly the viewmodels were no longer "in sync".

In my understanding and according to the docs, if Flow is the return type from a room database, then changes are streamed. And it worked exactly like that, once the database changed, the viewmodel was notifed and the new value was collected.

Why were they not "in sync" when multiple instances of the repository were used?

It was my understanding as well that room databases are Singleton, and so I blamed the repository instance difference. Or is this perhaps related to caching the writes ?

Can anyone explain what am I getting wrong in all this?

Edit:

The fix I was referring to is make both viewmodels use the same instance of repository.

Ait-Gacem Nabil
  • 165
  • 3
  • 12

1 Answers1

0

I think the short answer is that Room is NOT a singleton - you can have multiple instances of it which explains two different sources of truth.

Sources:

ryankuck
  • 320
  • 3
  • 15
  • Okay so if we assume it is not a singleton , shouldn't the flow be updated everytime the database is updated? because indeed the data _is_ going to a single .db file on the filesystem no matter which instance of Room i use. I think i am missing something. – Ait-Gacem Nabil Aug 31 '23 at 18:51
  • 1
    Okay I just looked in the docs and found this https://developer.android.com/reference/kotlin/androidx/room/RoomDatabase.Builder#enableMultiInstanceInvalidation() – Ait-Gacem Nabil Aug 31 '23 at 18:57