Liron Lavi
Liron Lavi

Reputation: 431

Dart's Future Interface (doWhile, microtask and sync)

Haven't seen a lot of info about it online...

What are the possible use cases in which I'd want to use, either Future.doWhile, Future.microtask or Future.sync?

Future.sync

A lot of times after a button press for example, I'd want a Future to happen immediately, but I wouldn't want it to block the UI, is that a good use case for Future.sync or is that better to use Future and let dart handle when thing will get executed?

Upvotes: 0

Views: 553

Answers (1)

TheMisir
TheMisir

Reputation: 4279

I'd want a Future to happen immediately...

You can't make Future to happen immediately because it needs some time to be executed. Instead you can block UI thread while future is executing. The pseudo code looks like that:

T runSync<T>(Future<T> future) {
  while (future.running) sleep(10);
  return future.result;
}

This will block your ui thread. That's why we are using Futures. Futures used for specific tasks that's not resolved immediately (usually I/O tasks, eg: network requests, file read/write) to get notified when future resolves without blocking UI thread.

Here's how I'm handling futures without blocking UI thread:

class MyState extends State<..> {
  bool _running = false;
  
  Future<String> doTask() async {
    // some long running IO tasks
    return 'Hello world';
  }

  Future handlePress() async {
    setState(() { _running = true; });
    try {
      await doTask();
    } finally {
      if (mounted) {
        setState(() { _running = false; });
      }
    }
  }

  Widget build(BuildContext context) {
    return FlatButton(
      child: Text('Execute'),
      // Disable button if task is currently running to block parallel calls (for example sending same http request twice)
      onPressed: _running ? null : handlePress,
    );
  }
}

In this code when user presses FlatButton I'm setting _running to true to disable FlatButton until Future is running.

Upvotes: 1

Related Questions