Created
June 8, 2022 08:14
-
-
Save PlugFox/fdc7fe1dbff6df70293e54df3ad05f71 to your computer and use it in GitHub Desktop.
Creating new isolate in dart and communicate with it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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