expectStateSequence method

Future<void> expectStateSequence(
  1. List<LxState> expected, {
  2. Duration timeout = const Duration(seconds: 5),
})

Verifies that the state stream emits exactly expected in order.

Strict: throws StateError immediately if an unexpected state arrives. Throws TimeoutException if the full sequence is not observed within timeout (default 5 s).

An empty expected list completes immediately.

Implementation

Future<void> expectStateSequence(
  List<LxState> expected, {
  Duration timeout = const Duration(seconds: 5),
}) {
  if (expected.isEmpty) return Future.value();

  final completer = Completer<void>();
  var index = 0;
  late StreamSubscription<LxState> sub;

  sub = state.listen((current) {
    if (completer.isCompleted) return;

    if (current != expected[index]) {
      sub.cancel();
      completer.completeError(StateError(
        'expectStateSequence: expected ${expected[index]} at index $index '
        'but got $current. Full expected sequence: $expected',
      ));
      return;
    }

    index++;
    if (index == expected.length) {
      sub.cancel();
      completer.complete();
    }
  });

  return completer.future.timeout(timeout, onTimeout: () {
    sub.cancel();
    throw TimeoutException(
      'expectStateSequence timed out after $timeout. '
      'Received $index of ${expected.length} expected states. '
      'Expected: $expected',
      timeout,
    );
  });
}