MdYamlDocLoader: Avoid starting the isolate multiple times

Man, there is a lot of locking that I hadn't even thought of while
writing all of this code.
This commit is contained in:
Vishesh Handa
2020-03-15 00:26:14 +01:00
parent d8464ff64f
commit 4a9e2f59d0
3 changed files with 20 additions and 4 deletions

View File

@ -1,6 +1,8 @@
import 'dart:io'; import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
import 'package:synchronized/synchronized.dart';
import 'package:gitjournal/core/md_yaml_doc.dart'; import 'package:gitjournal/core/md_yaml_doc.dart';
import 'package:gitjournal/core/md_yaml_doc_codec.dart'; import 'package:gitjournal/core/md_yaml_doc_codec.dart';
@ -9,13 +11,19 @@ class MdYamlDocLoader {
ReceivePort _receivePort = ReceivePort(); ReceivePort _receivePort = ReceivePort();
SendPort _sendPort; SendPort _sendPort;
var _loadingLock = Lock();
Future<void> _initIsolate() async { Future<void> _initIsolate() async {
if (_isolate != null) return; if (_isolate != null) return;
return await _loadingLock.synchronized(() async {
if (_isolate != null) return;
_isolate = await Isolate.spawn(_isolateMain, _receivePort.sendPort); _isolate = await Isolate.spawn(_isolateMain, _receivePort.sendPort);
var data = await _receivePort.first; var data = await _receivePort.first;
assert(data is SendPort); assert(data is SendPort);
_sendPort = data as SendPort; _sendPort = data as SendPort;
});
} }
Future<MdYamlDoc> loadDoc(String filePath) async { Future<MdYamlDoc> loadDoc(String filePath) async {

View File

@ -640,6 +640,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.0.5" version: "1.0.5"
synchronized:
dependency: "direct main"
description:
name: synchronized
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.0"
term_glyph: term_glyph:
dependency: transitive dependency: transitive
description: description:

View File

@ -36,6 +36,7 @@ dependencies:
connectivity: ^0.4.6+1 connectivity: ^0.4.6+1
flutter_emoji: ">= 2.0.0" flutter_emoji: ">= 2.0.0"
git_url_parse2: ^0.0.1 git_url_parse2: ^0.0.1
synchronized: ^2.2.0
dev_dependencies: dev_dependencies:
flutter_launcher_icons: "^0.7.2" flutter_launcher_icons: "^0.7.2"