@@ -118,6 +118,7 @@ class PowerSyncDatabaseImpl
118118 }
119119
120120 @override
121+ @internal
121122
122123 /// Connect to the PowerSync service, and keep the databases in sync.
123124 ///
@@ -134,10 +135,11 @@ class PowerSyncDatabaseImpl
134135
135136 // Disconnect if connected
136137 await disconnect ();
137- disconnecter = AbortController ();
138+ final disconnector = AbortController ();
139+ disconnecter = disconnector;
138140
139141 await isInitialized;
140- final dbref = database.isolateConnectionFactory ();
142+ final dbRef = database.isolateConnectionFactory ();
141143 ReceivePort rPort = ReceivePort ();
142144 StreamSubscription ? updateSubscription;
143145 rPort.listen ((data) async {
@@ -161,7 +163,7 @@ class PowerSyncDatabaseImpl
161163 updateSubscription = throttled.listen ((event) {
162164 port.send (['update' ]);
163165 });
164- disconnecter ? .onAbort.then ((_) {
166+ disconnector .onAbort.then ((_) {
165167 port.send (['close' ]);
166168 }).ignore ();
167169 } else if (action == 'uploadCrud' ) {
@@ -197,11 +199,11 @@ class PowerSyncDatabaseImpl
197199 logger.severe ('Sync Isolate error' , message);
198200
199201 // Reconnect
200- baseConnect (connector: connector);
202+ connect (connector: connector, crudThrottleTime : crudThrottleTime );
201203 });
202204
203205 disconnected () {
204- disconnecter ? .completeAbort ();
206+ disconnector .completeAbort ();
205207 disconnecter = null ;
206208 rPort.close ();
207209 // Clear status apart from lastSyncedAt
@@ -220,7 +222,7 @@ class PowerSyncDatabaseImpl
220222 }
221223
222224 Isolate .spawn (_powerSyncDatabaseIsolate,
223- _PowerSyncDatabaseIsolateArgs (rPort.sendPort, dbref , retryDelay),
225+ _PowerSyncDatabaseIsolateArgs (rPort.sendPort, dbRef , retryDelay),
224226 debugName: 'PowerSyncDatabase' ,
225227 onError: errorPort.sendPort,
226228 onExit: exitPort.sendPort);
@@ -274,12 +276,17 @@ Future<void> _powerSyncDatabaseIsolate(
274276 final upstreamDbClient = args.dbRef.upstreamPort.open ();
275277
276278 CommonDatabase ? db;
277- rPort.listen ((message) {
279+ final Mutex mutex = args.dbRef.mutex.open ();
280+ rPort.listen ((message) async {
278281 if (message is List ) {
279282 String action = message[0 ];
280283 if (action == 'update' ) {
281284 updateController.add ('update' );
282285 } else if (action == 'close' ) {
286+ // The SyncSqliteConnection uses this mutex
287+ // It needs to be closed before killing the isolate
288+ // in order to free the mutex for other operations.
289+ await mutex.close ();
283290 db? .dispose ();
284291 updateController.close ();
285292 upstreamDbClient.close ();
@@ -318,7 +325,6 @@ Future<void> _powerSyncDatabaseIsolate(
318325 }
319326
320327 runZonedGuarded (() async {
321- final mutex = args.dbRef.mutex.open ();
322328 db = await args.dbRef.openFactory
323329 .open (SqliteOpenOptions (primaryConnection: false , readOnly: false ));
324330 final connection = SyncSqliteConnection (db! , mutex);
0 commit comments