Using drift from multiple isolates and databases with watch #2815
-
Hello, I'm using the Drift feature of running in a separate Isolate to be accessed via IsolateNameServer: Future<DriftIsolate> createIsolate() async {
final token = RootIsolateToken.instance;
return await DriftIsolate.spawn(() {
BackgroundIsolateBinaryMessenger.ensureInitialized(token!);
return LazyDatabase(() async {
final dbFolder = await getApplicationDocumentsDirectory();
final path = p.join(dbFolder.path, 'app_database.db');
return NativeDatabase(File(path), logStatements: true);
});
});
}
//...
@DriftDatabase(tables: [SomeTable])
class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
@override
int get schemaVersion => 1;
}
LazyDatabase _openConnection() {
driftRuntimeOptions.dontWarnAboutMultipleDatabases = true; // different queryexecutor used for each database
return LazyDatabase(() async {
final di = DriftIsolate.fromConnectPort(
IsolateNameServer.lookupPortByName('drift_isolate')!);
final conn = await di.connect();
return conn.executor;
});
}
//... main
var di = await createIsolate();
IsolateNameServer.registerPortWithName(di.connectPort, "drift_isolate");
//... some widget
late AppDatabase db;
late Stream<List<SomeTableData>> someStream;
@override
void initState() {
super.initState();
db = AppDatabase();
someStream = db.select(db.someTable).watch();
}
@override
void dispose() {
super.dispose();
db.close();
}
//... build
StreamBuilder(
stream: someStream,
builder: ...,
)
//... some code in a different isolate with a different instance of AppDatabase
await db.into(db.someTable).insert(...); The initial |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
If everything is correctly setup, you don't need |
Beta Was this translation helpful? Give feedback.
-
No, I am only calling it once in main. I am opening multiple databases each connecting to the
Yes, as far as I am aware, there is only one
I am not, the |
Beta Was this translation helpful? Give feedback.
Thank you, using one AppDatabase per isolate resolved it For Some Reason™.