Need some pointers using MoorIsolate #1407
-
Hello, I'm trying to use isolates in my app to use the database, but something is going wrong. For a bit of context, the app uses a Moor database, from which it streams several values into the front-end ( Both when loading from my main isolate or from another isolate I spawned using the // function from the documentation
DatabaseConnection _backgroundConnection() {
// construct the database. You can also wrap the VmDatabase in a "LazyDatabase" if you need to run
// work before the database opens.
final database = VmDatabase.memory();
return DatabaseConnection.fromExecutor(database);
}
doThingsInIsolate() async {
// create the isolate with the database
MoorIsolate isolate = await MoorIsolate.spawn(_backgroundConnection);
DatabaseConnection connection = await isolate.connect();
final MyDatabase db = MyDatabase.connect(connection);
print('database is $db'); // instance of 'MyDatabase'
print('the items: ${await db.allItems().get()}'); // expected to return [Item<>], but returns []
// the actual DB stuff I want to do goes here
// intermediate prints happen fine, but the database remains untouched
await doActualDatabaseInteractions();
db.close();
isolate.shutdownAll();
} If there's anything clearly wrong, I would love to know. If there is some working example code I can take a look at, which shows how to work with these, that would also be very helpful. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Are you inserting data in your database's migration? If you're using a Apart from that, the code looks correct to me though. |
Beta Was this translation helpful? Give feedback.
Are you inserting data in your database's migration? If you're using a
VmDatabase.memory()
you'll get a clean in-memory database for eachMoorIsolate.spawn
, it would not get persisted anywhere. So it's not entirely unexpected thatallItems()
would return an empty list after opening a fresh database. You can re-use the existingVmDatabase
you were using before isolates in_backgroundConnection()
. When using things likepath_provider
, you'll also need to callFlutterWidgetsBinding.ensureInitialized()
in the background isolate to setup platform channels.Apart from that, the code looks correct to me though.