Skip to content

Commit

Permalink
fix: Prevent creation of multiple isolates when IrisMethodChannel.ini…
Browse files Browse the repository at this point in the history
…tialize is called multiple times simultaneously
  • Loading branch information
littleGnAl committed Apr 18, 2024
1 parent 28bbdc9 commit f9e5bf3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/src/iris_method_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,20 @@ import 'package:iris_method_channel/src/platform/iris_method_channel_internal.da

class CallOnce {
Completer<void> _completer = Completer<void>();
bool _isRunning = false;

Future<void> callOnce(Future<void> Function() func) async {
if (!_completer.isCompleted) {
if (!_completer.isCompleted && !_isRunning) {
try {
_isRunning = true;
await func();
} catch (e) {
_completer = Completer<void>();
_isRunning = false;
rethrow;
}
_completer.complete();
_isRunning = false;
}
return _completer.future;
}
Expand Down
13 changes: 13 additions & 0 deletions test/iris_method_channel_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ void main() {
await irisMethodChannel.dispose();
});

test('only initialize once when called simultaneously', () async {
for (int i = 0; i < 5; ++i) {
irisMethodChannel.initilize([]);
}
// Wait for the 5 times calls of `irisMethodChannel.initilize` are completed.
await Future.delayed(const Duration(milliseconds: 1000));
final callRecord1 = messenger.callApiRecords
.where((e) => e.methodCall.funcName == 'createApiEngine');
expect(callRecord1.length, 1);

await irisMethodChannel.dispose();
});

test('can re-initialize after dispose', () async {
await irisMethodChannel.initilize([]);
await irisMethodChannel.initilize([]);
Expand Down

0 comments on commit f9e5bf3

Please sign in to comment.