Skip to content

Instantly share code, notes, and snippets.

@tomalabaster
Created January 3, 2021 20:32
Show Gist options
  • Save tomalabaster/2aa4a16cd06ff7a76f8d0250792523e5 to your computer and use it in GitHub Desktop.
Save tomalabaster/2aa4a16cd06ff7a76f8d0250792523e5 to your computer and use it in GitHub Desktop.
A utility method for waiting for a bloc to yield a specific state.
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
class BlocClosedWithoutYieldingStateException implements Exception {}
Future<T> waitForStateFromBloc<T>({
@required Bloc bloc,
}) {
final completer = Completer<T>();
if (bloc.state is T) {
completer.complete(bloc.state);
return completer.future;
}
StreamSubscription blocSubscription;
blocSubscription = bloc.listen(
(state) {
if (state is T) {
completer.complete(state);
blocSubscription.cancel();
}
},
onDone: () {
completer.completeError(BlocClosedWithoutYieldingStateException());
blocSubscription.cancel();
},
cancelOnError: true,
);
return completer.future;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment