waitForState method

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

Completes when targetState is observed on the state stream.

Resolves immediately if the current state already matches. Throws TimeoutException if timeout elapses (default 5 s).

Implementation

Future<void> waitForState(
  LxState targetState, {
  Duration timeout = const Duration(seconds: 5),
}) {
  final completer = Completer<void>();
  late StreamSubscription<LxState> sub;

  sub = state.listen((current) {
    if (!completer.isCompleted && current == targetState) {
      sub.cancel();
      completer.complete();
    }
  });

  return completer.future.timeout(timeout, onTimeout: () {
    sub.cancel();
    throw TimeoutException(
      'waitForState($targetState) timed out after $timeout. '
      'No matching state was observed.',
      timeout,
    );
  });
}