Advantages of Future.of () compared to Timer.run () in a dart?

Dart has many ways to create, process, and return asynchronous functions. One of the most common methods:

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 directly, for example:

 import 'dart:async'; return new Future.of(() => doSomethingHere()); 

I am aware that the version of Timer.run() can be canceled using the return value of the static method. And that the version of new Future.of() slightly smaller than the code, is there a particular benefit from using new Future.of() over Timer.run() (or vice versa). Or the benefits I just mentioned?

+4
source share
2 answers

Future.of returns the future, Timer.run nothing. For me, this is the main difference.

I use Future.of if I want to return the value as Future.

I use Timer.run if I want to run some function later and it doesn't matter to me what value it produces.

One big difference is that the function starts.

For Future.of function runs in the current event loop, and only its value becomes available in the next event loop.

For Timer.run function runs in the next event loop.

+3
source

Do not forget that these are two different things. Timer can be used anywhere for many purposes. It can be used on the client side to wait for the layout, for example, before running more code. Thus, this may have nothing to do with futures. I sometimes use a timer in client code to wait for a layout.

Timer is a general class for delaying the execution of some code. It doesn't matter if it has anything to do with futures or not. Another example would be client-side animation. It has nothing to do with futures or data asynchrony.

Futures, however, are mones that help you program asynchronous programs. Basically a replacement for passing simple callback functions.

Use new Future.of() when writing asynchronous programs, and this is appropriate for your situation (the same thing happens with new Future.immediate() .

Use the Timer class if you want to delay the execution of some code.

If you want to use futures for asynchronous programming and at the same time delay code, forget about the timer class if you do not need a real delay (more than 0 / next event).

+2
source

All Articles