Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Finalizer for MLKitScanDecoder #2937

Merged
merged 2 commits into from
Sep 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/smooth_app/lib/pages/scan/mkit_scan_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ class MLKitScanDecoder {
scanMode: scanMode,
);

/// Ensures the dispose() method is called if this class is GC'ed.
static final Finalizer<_MLKitScanDecoderMainIsolate> _finalizer =
Finalizer<_MLKitScanDecoderMainIsolate>(
(_MLKitScanDecoderMainIsolate isolate) => isolate.dispose(),
);

final DevModeScanMode scanMode;
final _MLKitScanDecoderMainIsolate _mainIsolate;

Expand All @@ -40,11 +46,18 @@ class MLKitScanDecoder {
// OK -> continue
}

/// The next call with recreate the isolate if necessary.
/// Re-attaching it to the finalizer is mandatory.
if (_mainIsolate.isDisposed) {
_finalizer.attach(this, _mainIsolate, detach: this);
}

return _mainIsolate.decode(image);
}

Future<void> dispose() async {
_mainIsolate.dispose();
_finalizer.detach(this);
Logs.d(tag: 'MLKitScanDecoder', 'Disposed');
}
}
Expand Down Expand Up @@ -150,6 +163,12 @@ class _MLKitScanDecoderMainIsolate {
_isolate?.kill(priority: Isolate.immediate);
_isolate = null;
}

bool get isDisposed =>
_isIsolateInitialized == false &&
_completer == null &&
_sendPort == null &&
_isolate == null;
}

// ignore: avoid_classes_with_only_static_members
Expand Down