How to use drift background tasks with shareAcrossIsolates #3229
-
I am considering an application that uses Bluetooth in the background, writes its connection status to a database, and reflects it in the UI. I learned that drift has an option to share database connections between multiple isolates called shareAcrossIsolates. I use below package
void main() {
FlutterForegroundTask.initCommunicationPort();
// for main isolate
Get.put<LocalDatabase>(LocalDatabase());
runApp(const ProviderScope(child: MainApp()));
}
@pragma('vm:entry-point')
void startCallback() {
FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}
class MyTaskHandler extends TaskHandler {
// Called when the task is started.
@override
void onStart(DateTime timestamp) {
// for background isolate
Get.put<LocalDatabase>(LocalDatabase());
print('onStart');
}
} @DriftDatabase(tables: [
AppSettings,
BleDevices,
])
class LocalDatabase extends _$LocalDatabase {
LocalDatabase()
: super(driftDatabase(
name: 'local_database',
native: const DriftNativeOptions(shareAcrossIsolates: true),
));
@override
int get schemaVersion => 1;
}
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
In fact, both UI and background tasks perform queries such as |
Beta Was this translation helpful? Give feedback.
-
Thanks for the report! I was under the assumption that isolates sharing an Drift can in principle work around this issue by serializing messages sent between different isolates into simple Dart objects that can always be sent. That flag is just somewhat hidden and not exported by This isn't easy to test since it requires independent isolate groups, could you check whether adding these dependency overrides fixes the issue for you? dependency_overrides:
drift:
git:
url: https://github.com/simolus3/drift.git
ref: develop
path: drift
drift_flutter:
git:
url: https://github.com/simolus3/drift.git
ref: develop
path: drift_flutter |
Beta Was this translation helpful? Give feedback.
Argh, I had them the wrong way around. This was fixed in 14202c8, I also managed to find an easier way to test this. Let me know if you run into any other issues with that.