0

I am trying to update long running(while true) isolate. the idea is call update everywhere on main or update that value on future.

void main() async {
  final ReceivePort p = ReceivePort();
  var events = StreamQueue<dynamic>(p);
  SendPort sendPort = await events.next;
  await Isolate.spawn(longTask, p.sendPort);
  sendPort.send(30);

  Future.delayed(Duration(seconds: 10), (() {
    sendPort.send(10);
  }));
  Future.delayed(Duration(seconds: 50), (() {
    sendPort.send(30);
  }));
}

Future<void> longTask(SendPort p) async {
  final commandPort = ReceivePort();
  p.send(commandPort.sendPort);

  //###############################################
  // the idea is this loop will call function each second  
  while (true) {
    // how to get value 30 20 10  ?
    // here
    sleep(const Duration(seconds: 1));
  }
}

I cannot using await for because loop must running without stop

 await for (var d in commandPort) {
    print(d);
 }
Dwiyi
  • 638
  • 7
  • 17
  • 1
    I'm not entirely sure I understand the question, but you could do a `commandPort.forEach(...)` without awaiting it. Also don't use [sleep](https://api.dart.dev/stable/2.18.6/dart-io/sleep.html), use `await Future.delayed(duration)` instead. – mmcdon20 Jan 13 '23 at 05:45
  • @mmcdon20 sorry my english is not good. using `commandPort.forEach(...)` will depend how many value will send and will stop. the idea is loop must running and get update value. – Dwiyi Jan 13 '23 at 06:01
  • @mmcdon20 thanks bro, using `await Future.delayed(duration)` work. using "sleep" value or variable not updated. why is it ? – Dwiyi Jan 13 '23 at 07:25
  • If you read the documentation for [sleep](https://api.dart.dev/stable/2.18.6/dart-io/sleep.html). It says "Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call". You don't want to use `sleep` in an asynchronous program for that reason. – mmcdon20 Jan 13 '23 at 07:29
  • Port communication is handled as top-level events of the event loop. If you have a `while (true) ...` loop with no async `await`s in it, that code will never go back to the event loop, so you will never be notified of the port messages waiting for you. The `sleep` function just suspends the entire isolate, including the event loop. It changes nothing, except time spent. – lrn Jan 13 '23 at 16:18

0 Answers0