@@ -191,13 +191,24 @@ class PowerSyncDatabase with SqliteQueries implements SqliteConnection {
191191 /// Throttle time between CRUD operations
192192 /// Defaults to 10 milliseconds.
193193 Duration crudThrottleTime = const Duration (milliseconds: 10 )}) async {
194- _connectMutex.lock (() =>
195- _connect (connector: connector, crudThrottleTime: crudThrottleTime));
194+ Zone current = Zone .current;
195+
196+ Future <void > reconnect () {
197+ return _connectMutex.lock (() => _connect (
198+ connector: connector,
199+ crudThrottleTime: crudThrottleTime,
200+ // The reconnect function needs to run in the original zone,
201+ // to avoid recursive lock errors.
202+ reconnect: current.bindCallback (reconnect)));
203+ }
204+
205+ await reconnect ();
196206 }
197207
198208 Future <void > _connect (
199209 {required PowerSyncBackendConnector connector,
200- required Duration crudThrottleTime}) async {
210+ required Duration crudThrottleTime,
211+ required Future <void > Function () reconnect}) async {
201212 await initialize ();
202213
203214 // Disconnect if connected
@@ -266,7 +277,9 @@ class PowerSyncDatabase with SqliteQueries implements SqliteConnection {
266277 logger.severe ('Sync Isolate error' , message);
267278
268279 // Reconnect
269- connect (connector: connector);
280+ // Use the param like this instead of directly calling connect(), to avoid recursive
281+ // locks in some edge cases.
282+ reconnect ();
270283 });
271284
272285 disconnected () {
@@ -532,7 +545,7 @@ Future<void> _powerSyncDatabaseIsolate(
532545
533546 CommonDatabase ? db;
534547 final mutex = args.dbRef.mutex.open ();
535- StreamingSyncImplementation ? _sync ;
548+ StreamingSyncImplementation ? openedStreamingSync ;
536549
537550 rPort.listen ((message) async {
538551 if (message is List ) {
@@ -548,7 +561,7 @@ Future<void> _powerSyncDatabaseIsolate(
548561 updateController.close ();
549562 upstreamDbClient.close ();
550563 // Abort any open http requests, and wait for it to be closed properly
551- await _sync ? .abort ();
564+ await openedStreamingSync ? .abort ();
552565 // No kill the Isolate
553566 Isolate .current.kill ();
554567 }
@@ -596,7 +609,7 @@ Future<void> _powerSyncDatabaseIsolate(
596609 uploadCrud: uploadCrud,
597610 updateStream: updateController.stream,
598611 retryDelay: args.retryDelay);
599- _sync = sync ;
612+ openedStreamingSync = sync ;
600613 sync .streamingSync ();
601614 sync .statusStream.listen ((event) {
602615 sPort.send (['status' , event]);
0 commit comments