Description
Documentation for Future.value
says:
Lines 328 to 329 in 99919c6
However, the implementation calls _Future<T>.immediate
Lines 348 to 349 in 99919c6
It schedules a microtask to complete the future:
sdk/sdk/lib/async/future_impl.dart
Lines 269 to 270 in 99919c6
sdk/sdk/lib/async/future_impl.dart
Lines 577 to 599 in 99919c6
sdk/sdk/lib/async/future_impl.dart
Lines 636 to 641 in 99919c6
Scheduling a microtask is slower than just completing future synchronously. It also doesn't fully follow the documented behavior (the created Future is not fully completed until the microtask runs).
A good example of users struggling with this behavior is a SynchronousFuture
from Flutter:
/// A [Future] whose [then] implementation calls the callback immediately.
///
/// This is similar to [Future.value], except that the value is available in
/// the same event-loop iteration.
///
/// ⚠ This class is useful in cases where you want to expose a single API, where
/// you normally want to have everything execute synchronously, but where on
/// rare occasions you want the ability to switch to an asynchronous model. **In
/// general use of this class should be avoided as it is very difficult to debug
/// such bimodal behavior.**
class SynchronousFuture<T> implements Future<T> {
It looks like SynchronousFuture
would not be needed if Future.value
would complete the Future synchronously (and maybe Future.then
would also avoid scheduling an extra microtask for the completed future).
In addition to Future.value
, it would be nice to revise other places where the current Future implementation schedules extra unnecessary microtasks when value is already available / future is already completed.