隔离
概述
该软件包简化了隔离区之间的创建和交互。它封装了整个样板代码,只留下开发人员通过类似于两个流控制器的 API 进行传输。
该软件包还有助于在隔离区之间保留类型和传递异常。
用法
JSON 解析器
import 'dart:async';
import 'dart:convert' show jsonDecode;
import 'package:isolation/isolation.dart';
typedef JsonMap = Map<String, Object?>;
/// Main isolate
void main() => Future<void>(() async {
// Create a new isolate controller
final controller = IsolateController<String, JsonMap>(
_parser, // Isolate function
lazy: true, // The isolate will not be created until the first message
)
// Add few messages to the isolate:
..add('{}')
..add('{"field": 123}')
..add('{"fizz": "buzz", "value": 2, "undefined": null}');
// Listen messages from slave isolate
await controller.stream.take(3).forEach(print);
// Gracefully closing connection and finally kill slave isolate
await controller.close(force: false);
});
/// Slave isolate for parsing JSON, where you can subscribe to the stream
/// from the main isolate and send the result back through the controller.
Future<void> _parser(IsolateController<JsonMap, String> controller) =>
controller.stream.forEach((json) {
final result = jsonDecode(json) as Object?;
(result is JsonMap)
? controller.add(result)
: controller.addError(const FormatException('Invalid JSON'));
});
安装
将以下内容添加到您的 pubspec.yaml 文件中,以便能够进行代码生成
dependencies:
isolation: any
然后运行
dart pub get
或者
flutter pub get
覆盖范围
更新日志
有关所有发行说明,请参阅更新日志。