3

I'm just getting to know about Android Room Database.

When I was using Realm Database, I had to care if Realm DB instance was opened or closed. So I managed it by .use in my kotlin code.

RealmProvider(context).getDatabase().use { database ->
                if (database == null) {
                    it.onError(Exception("DataBase Open Error !"))
                } else {
                    database.executeTransaction { realm -> realm.insert(SomeData) }
                    it.onComplete()
                }
            }

However; in Room DB, no one use roomDatabase.close() in their codes.

So I'm wondering when Room DB is closed and opened and also when db instance is allocated and free on RAM memory.

Nasang
  • 43
  • 1
  • 5
  • 3
    Usually everyone create singleton instance of db, and i guess (im not super expert) it doesn't worth keep close and opening it. Interesting question – Dak28 Dec 03 '19 at 11:10
  • 1
    I have looked into the Android Profiler and the memory usage is ranging in 120 MB to 150 MB after several oprations, also I wasn't closing the database, even then there was no some sort of memory leak. – Kaushik Burkule Dec 03 '19 at 11:24
  • Did you try by closing and reopening it? – Dak28 Dec 03 '19 at 11:28
  • @Dak28 yes, when I wanted to check the db size, I closed it then open. Except this case, I didn't close Room DB. I just wondered why I don't need to close Room DB compared to Realm DB. – Nasang Dec 04 '19 at 03:17

1 Answers1

0

No, according to https://stackoverflow.com/a/7739454/1090523 the system will handle the closing of the database connection when the app is closed. No leak will occur, and it is also more performant to keep a connection open and reuse it than to keep opening and closing connections.

Chapz
  • 605
  • 7
  • 13