Created
January 3, 2021 20:32
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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