Reputation: 6312
Dart has many ways of creating, processing and returning async functions. One of the most common methods is to:
import 'dart:async';
var completer = new Completer();
// Previously this would have been new Timer(0, () => ....);
Timer.run(() => completer.complete(doSomethingHere()));
return completer.future;
However dart also provides a constructor for Future's directly such as:
import 'dart:async';
return new Future.of(() => doSomethingHere());
I am aware that the Timer.run()
version may be cancelled using the return value of the static method. And that the new Future.of()
version is slightly less code, is there a particular benefit to using new Future.of()
over Timer.run()
(or vice versa). Or are the benefits simply those that I just mentioned?
Upvotes: 4
Views: 1791
Reputation: 120579
Future.of
returns a Future, Timer.run
does not return anything. To me, this is the main difference.
I use Future.of
if I want to return a value as a Future.
I use Timer.run
if I want to run some function later, and I don't care about the value that it produces.
One big difference is when the function is run, though.
For Future.of
, the function is run in the current event loop, and only its value is made available in the next event loop.
For Timer.run
, the function is run in the next event loop.
Upvotes: 3
Reputation: 30222
Don't forget that they are two different things. Timer
can be used anywhere for so many purposes. It could be used on the client-side for waiting for layout to happen before running more code, for example. So, it may not have anything to do with futures. I use the timer sometimes in client-side code to wait for a layout.
Timer is a generic class for delaying the running of some code. No matter whether it has anything to do with futures or not. Another example could be client-side animations. Nothing to do with futures or dealing with data asynchronously.
Futures, however, are monads that help you to program asynchronous programs. Basically a replacement to passing plain callback functions.
Use new Future.of()
when writing asynchronous programs and it suits your situation (the same goes with new Future.immediate()
.
Use the Timer
class if you want to delay the running of some code.
If what you want to do is to use futures for asynchronous programming and at the same time delay the code, forget the timer class unless you need some real delay (more than 0/next event).
Upvotes: 2