Advertisement
chayanforyou

isolate_flutter

Mar 4th, 2024 (edited)
840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.87 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:isolate';
  4.  
  5. class FileRecorder {
  6.   late String _filePath;
  7.   late SendPort _sendPort;
  8.   late ReceivePort _receivePort;
  9.   late Isolate _isolate;
  10.   final Completer<void> _isolateReady = Completer.sync();
  11.  
  12.   Future<void> start(String filePath) async {
  13.     _filePath = filePath;
  14.     _receivePort = ReceivePort();
  15.     _receivePort.listen(_handleResponsesFromIsolate);
  16.     _isolate = await Isolate.spawn(_startRemoteIsolate, _receivePort.sendPort);
  17.   }
  18.  
  19.   Future<void> record(List<int> message) async {
  20.     await _isolateReady.future;
  21.     _sendPort.send(message);
  22.   }
  23.  
  24.   Future<void> stop() async {
  25.     await _isolateReady.future;
  26.     _sendPort.send(true);
  27.   }
  28.  
  29.   void _handleResponsesFromIsolate(dynamic message) {
  30.     if (message is SendPort) {
  31.       _sendPort = message;
  32.       _isolateReady.complete();
  33.     } else if (message is bool) {
  34.       if (message == true) {
  35.         _receivePort.close();
  36.         _isolate.kill(priority: Isolate.immediate);
  37.       }
  38.     } else if (message is List<int>) {
  39.       final contents = '${message.join(',')},';
  40.       File file = File(_filePath);
  41.       file.writeAsStringSync(contents, mode: FileMode.append);
  42.     }
  43.   }
  44.  
  45.   static void _startRemoteIsolate(SendPort port) {
  46.     final receivePort = ReceivePort();
  47.     port.send(receivePort.sendPort);
  48.  
  49.     receivePort.listen((dynamic message) {
  50.       port.send(message);
  51.     });
  52.   }
  53. }
  54.  
  55. void main() async {
  56.   final ecg = FileRecorder();
  57.   await ecg.start('hello.txt');
  58.  
  59.   ecg.record(List.generate(1000000, (i) => i));
  60.   ecg.record(List.generate(1000000, (i) => i + 1000000));
  61.   ecg.record(List.generate(1000000, (i) => i + 2000000));
  62.   ecg.record(List.generate(1000000, (i) => i + 3000000));
  63.   ecg.record(List.generate(1000000, (i) => i + 4000000));
  64.   ecg.record(List.generate(1000000, (i) => i + 5000000));
  65.  
  66.   ecg.stop();
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement