Loading Data into the SQLiteDatabase in the onCreate() method of the SQLiteOpenHelper
from the CommonsWare Community archivesAt August 19, 2021, 6:42pm, Andr0id asked:
Hi All,
I’m creating a bunch of databases on the fly. I’m using the good’ol SQLite apis that Android has to offer.
I’m populating the databases in the onCreate method of the SQLiteOpenHelper like :-
override fun onCreate(db: SQLiteDatabase?) {
coroutineScope.launch{
try {
insertDataIntoTheDatabase(db) //fetch & insert data from the n/w
} catch (e: Exception) {
_logger.error("Error while creating objects inside the Database: $dbName!", e)
}
}
}
IMO this has a potential of a leak.
Just wanted to confirm if my understanding is correct.
At August 19, 2021, 9:34pm, mmurphy replied:
Possibly, though that is difficult to answer with just this code snippet. It comes down to where coroutineScope
is coming from and when it will get cleared.
I am more concerned about some architectural implications:
- Your comment suggests that a
SQLiteOpenHelper
is responsible for network I/O - Your code suggests that a
SQLiteOpenHelper
is holding aCoroutineScope
Off the cuff, I would do neither of those things. I would keep SQLiteOpenHelper
extremely lean. Network I/O and management of scopes is something that, IMHO, is not the responsibility of a database access utility class. A repository that uses the SQLiteOpenHelper
might also have a data source that does network I/O (e.g., a Retrofit-generated class) and might create child scopes of some suitable parent scope for coroutines.
At August 19, 2021, 9:54pm, Andr0id replied:
Thank you for the prompt response @mmurphy.
Yes, I’ve defined the Coroutine Scope within the SQLiteOpenHelper Class and plan to refactor this bit asap.
I too didn’t like the N/W call being made from the SQLiteOpenHelper
as well the SQLiteOpenHelper
holding a CoroutineScope
.