Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Created June 8, 2022 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugFox/fdc7fe1dbff6df70293e54df3ad05f71 to your computer and use it in GitHub Desktop.
Save PlugFox/fdc7fe1dbff6df70293e54df3ad05f71 to your computer and use it in GitHub Desktop.
Creating new isolate in dart and communicate with it
/// Creating new isolate and communicate with it
import 'dart:convert';
import 'dart:isolate';
import 'package:stream_transform/stream_transform.dart';
void main() => Future<void>(() async {
final receivePort = ReceivePort();
final stream = receivePort.asBroadcastStream();
final isolate = await Isolate.spawn<SendPort>(jsonParser, receivePort.sendPort);
final sendPort = await stream.whereType<SendPort>().first;
final jsonStream = stream.whereType<ParseResult>();
Future<Object> parse(String json) {
sendPort.send(json);
return jsonStream.firstWhere((e) => e.source == json).then<Object>((e) => e.result);
}
await Stream<Object>.fromFutures(<Future<Object>>[
parse('{"key":"value"}'),
parse('[1, 2, 3]'),
parse('{"list": ["a", "b", "c"]}'),
]).forEach(print);
receivePort.close();
isolate.kill();
});
void jsonParser(SendPort sendPort) {
final receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.where((Object? e) => e is String).cast<String>().forEach((json) {
sendPort.send(ParseResult(json, jsonDecode(json) as Object));
});
}
class ParseResult {
const ParseResult(this.source, this.result);
final String source;
final Object /* Map<String, Object?> or List<Object> */ result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment