init method
Opens (and if needed creates or migrates) the database, and starts saving study and task changes. Must be called before any other method. Does nothing if the database is already open.
Implementation
Future<void> init() async {
if (_database?.isOpen ?? false) return;
info('Initializing $runtimeType...');
_databasePath ??= await getDatabasesPath();
// open the database - make sure to use the same database across app (re)start
_database = await openDatabase(
databaseName,
version: DATABASE_VERSION,
singleInstance: true,
onCreate: (Database db, int version) async {
// when creating the database, create the tables
await _createStudyTable(db);
await _createTaskQueueTable(db);
debug('$runtimeType - $databaseName DB created');
},
onUpgrade: (Database db, int oldVersion, int newVersion) async {
if (oldVersion < 2) await _migrateToV2(db);
},
);
// Listen to changes to studies in the client repository so we can save them.
SmartphoneClientRepository().studyStatusEvents.listen((event) => updateStudy(event.study));
// Listen to changes to the app task queue so we can save them.
AppTaskController().userTaskEvents.listen((task) => saveUserTask(task));
info('$runtimeType - SQLite DB initialized - file: $databaseName');
}