Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 61 ยท Practice and Review

Practice: Async and Streams

Seven Dart exercises with solutions on Futures, Future.wait, timeouts, async* generators, stream pipelines, broadcast controllers and event-loop ordering.

Asynchronous code is where many learners lose confidence, because the order in which lines run no longer matches the order in which they are written. The cure is practice: write small programs, predict their output, and then check. This lesson has seven exercises on Future, async and await, streams, and the event loop, with solutions in real Dart (read-only on this site) and runnable TypeScript stand-ins built on Promises and async iterators.

If you need a refresher first, review Futures and async/await, Streams and The Event Loop. Try each exercise in DartPad or with dart run before you open the solution.

flowchart LR
    A["1 await in sequence<br/>vs Future.wait"] --> B["2 errors and fallbacks"]
    B --> C["3 timeouts"]
    C --> D["4 async* generator"]
    D --> E["5 stream pipeline"]
    E --> F["6 broadcast controller"]
    F --> G["7 predict the order"]

The exercises move from single futures to streams, and finish with the event-loop ordering puzzle.

Exercise 1: sequential versus parallel

Task. Write Future<int> slowDouble(int n) that waits 100 milliseconds and returns n * 2. Call it for 1, 2 and 3. First await the calls one after another, then start all three at once with Future.wait. Check which version takes at least 300 ms and which one finishes in about 100 ms.

Hint. Future.delayed(duration) simulates slow work. Future.wait takes a list of futures and returns a future of a list. A Stopwatch measures elapsed time.

Show the solution
DART
Future<int> slowDouble(int n) async {
  await Future<void>.delayed(const Duration(milliseconds: 100));
  return n * 2;
}

Future<void> main() async {
  final watch = Stopwatch()..start();

  final a = await slowDouble(1);
  final b = await slowDouble(2);
  final c = await slowDouble(3);
  print([a, b, c]);                              // [2, 4, 6]
  print('sequential: ${watch.elapsedMilliseconds >= 300}');   // true

  watch.reset();
  final results = await Future.wait([
    slowDouble(1),
    slowDouble(2),
    slowDouble(3),
  ]);
  print(results);                                // [2, 4, 6]
  print('parallel: ${watch.elapsedMilliseconds < 250}');       // true
}

Each await pauses main until that future finishes, so three awaits in a row add up their waiting times. Future.wait starts all three immediately and completes when the slowest one does. Use it when the calls do not depend on each other.

Exercise 2: errors and fallbacks

Task. Write Future<String> withFallback(Future<String> Function() action, String fallback). It runs the action. If the action throws an Exception, it returns the fallback. Whatever happens, it prints 'finished'. Test it with an action that succeeds and one that throws.

Hint. try, on Exception, and finally work in async functions exactly as in normal ones. Only await makes a failing future throw inside the try.

Show the solution
DART
Future<String> withFallback(
  Future<String> Function() action,
  String fallback,
) async {
  try {
    return await action();      // await is what lets try/catch see the error
  } on Exception {
    return fallback;
  } finally {
    print('finished');
  }
}

Future<void> main() async {
  print(await withFallback(() async => 'fresh data', 'cached'));
  print(await withFallback(() async => throw Exception('offline'), 'cached'));
}

If you wrote return action(); without await, the future would be returned to the caller before it completes, the try would be left immediately, and a later error would escape the catch. Also notice on Exception: it does not catch an Error such as a StateError, because those signal bugs, not expected conditions.

Exercise 3: giving up after a timeout

Task. Write a function slowLookup() that takes 2 seconds to return 'late answer'. Call it with a timeout of 200 ms so that, instead of waiting, the caller receives 'gave up'.

Hint. The timeout method on Future accepts an onTimeout callback. Without it, it throws a TimeoutException.

Show the solution
DART
Future<String> slowLookup() =>
    Future.delayed(const Duration(seconds: 2), () => 'late answer');

Future<void> main() async {
  final answer = await slowLookup().timeout(
    const Duration(milliseconds: 200),
    onTimeout: () => 'gave up',
  );
  print(answer);   // gave up
}

Timing out does not cancel the underlying work: the 2-second delay still runs in the background and its result is simply ignored. Dart futures cannot be cancelled, which is something to remember when the work has side effects.

The first stand-in runs the first three exercises. TypeScript Promises behave like Dart futures here, and Promise.all plays the role of Future.wait:

TypeScript Exercises 1 to 3 (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Exercise 4: an async generator

Task. Write Stream<int> countdown(int from) that emits from, from - 1, down to 1, with a 50 ms pause before each value. Consume it with await for and print 'liftoff' at the end.

Hint. A function marked async* returns a Stream; yield emits one value. Streams are covered in Streams.

Show the solution
DART
Stream<int> countdown(int from) async* {
  for (var i = from; i >= 1; i--) {
    await Future<void>.delayed(const Duration(milliseconds: 50));
    yield i;
  }
}

Future<void> main() async {
  await for (final n in countdown(3)) {
    print(n);                 // 3, 2, 1
  }
  print('liftoff');
}

The generator body runs lazily: it pauses at each yield until the consumer asks for the next value, and it only starts when someone listens. await for finishes when the stream closes, so 'liftoff' prints after the last number.

Exercise 5: a stream pipeline

Task. Starting from the numbers 1 to 6 as a stream, keep the even ones, square them, and print each result. Then compute the sum of the numbers 1 to 4 from a stream without a loop.

Hint. Streams have where and map, just like iterables, and a fold that returns a Future.

Show the solution
DART
Future<void> main() async {
  final evenSquares = Stream.fromIterable([1, 2, 3, 4, 5, 6])
      .where((n) => n.isEven)
      .map((n) => n * n);

  await for (final v in evenSquares) {
    print(v);                // 4, 16, 36
  }

  final total = await Stream.fromIterable([1, 2, 3, 4])
      .fold<int>(0, (sum, n) => sum + n);
  print(total);              // 10
}

Each stage returns a new stream, so the pipeline is lazy: values flow through one at a time. fold has to see every element, so it returns a Future that completes when the stream is done.

Exercise 6: a broadcast stream

Task. Create a StreamController<String>.broadcast(). Attach two listeners: the first stores messages as they arrive, the second stores them in upper case. Add 'hi' and 'there', close the controller, and print what each listener collected.

Hint. An ordinary stream allows one listener. A broadcast stream allows many, but listeners only receive events sent after they subscribe.

Show the solution
DART
import 'dart:async';

Future<void> main() async {
  final controller = StreamController<String>.broadcast();
  final plain = <String>[];
  final shouting = <String>[];

  controller.stream.listen(plain.add);
  controller.stream.listen((m) => shouting.add(m.toUpperCase()));

  controller.add('hi');
  controller.add('there');
  await controller.close();

  print(plain);      // [hi, there]
  print(shouting);   // [HI, THERE]
}

Subscribing before adding events matters: a listener that attaches later misses earlier events. Always close controllers you create; otherwise await for loops on them never finish.

Here are stand-ins for exercises 4 to 6. Async generators are TypeScript's version of async*, and for await is the counterpart of await for. The broadcast controller is a tiny hand-written class:

TypeScript Exercises 4 to 6 (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Exercise 7: predict the order

Task. Without running it, write down the order in which these lines print:

DART
import 'dart:async';

void main() {
  print('D');
  Future(() => print('A')).then((_) => print('B'));
  scheduleMicrotask(() => print('C'));
}

Hint. The event loop finishes the current synchronous code first, then drains the microtask queue, and only then takes the next item from the event queue. Future(...) puts its function on the event queue; scheduleMicrotask uses the microtask queue. A .then callback runs after its future completes.

Show the solution

The output is D, C, A, B.

  1. main runs to the end. It prints D straight away and queues two things: the future's function on the event queue, and the microtask.
  2. When main finishes, the microtask queue is emptied: C prints.
  3. The event loop takes the next event: the future's function runs and prints A. The future completes, which schedules its .then callback.
  4. B prints.

The rule of thumb: synchronous code first, then every pending microtask, then one event at a time (with microtasks drained after each).

sequenceDiagram
    participant M as main (sync)
    participant MQ as Microtask queue
    participant EQ as Event queue
    M->>M: print D
    M->>EQ: Future(print A)
    M->>MQ: print C
    MQ->>MQ: print C
    EQ->>EQ: print A, then B

Synchronous code, then microtasks, then events: the same order appears in browsers and Node.js.

JavaScript has the same two queues, so a stand-in shows the identical order. Run it, then change the order of the lines and predict again:

TypeScript Exercise 7: ordering puzzle (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The extra line end of main shows that even after the whole synchronous part is finished, C still comes before A.

Going further

  • Combine exercises 2 and 3: retry a failing action up to three times with a short pause (see Project: Typed REST Client for a full version).
  • Turn countdown into a broadcast stream with asBroadcastStream() and attach two listeners.
  • Use Future.wait with eagerError: true and observe when the first failure surfaces.
  • Write a Stream<int> ticker(Duration interval) using Stream.periodic, and stop it with take(5).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Three independent calls, each taking 100 ms, are awaited one after another. About how long does the sequence take?

    Each await waits for its future before the next call even starts, so the waits add up. Future.wait would start all three at once.
  2. 2. Why is return await action(); used inside a try block rather than return action();?

    Only an awaited future rethrows its error inside the try. Returning the unfinished future hands the error to the caller instead.
  3. 3. In exercise 7, why does C print before A?

    After the synchronous code finishes, the event loop drains the microtask queue before it processes the next event, such as the Future's callback.
  4. 4. A listener subscribes to a broadcast stream after two events were added. What does it receive?

    Broadcast streams do not buffer for late listeners. A new subscriber sees only future events.
  5. 5. What does a function marked async* return?

    An async* function is a generator for a Stream. yield sends a value to listeners, and the body only runs once someone listens.

Summary

  • Awaiting futures one by one adds their delays; Future.wait runs independent futures together.
  • Use try, on and finally around an await to handle async errors, and keep the await on the returned value.
  • timeout stops waiting, not working: Dart futures cannot be cancelled.
  • async* and yield build streams lazily; await for, where, map and fold consume and transform them.
  • Broadcast streams allow several listeners but replay nothing to late subscribers.
  • The event loop runs synchronous code, then all microtasks, then one event at a time.

Next, test your knowledge of the whole language with Dart Interview Questions.