You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.8KB

  1. import 'dart:async';
  2. import 'package:bloc/bloc.dart';
  3. import 'package:equatable/equatable.dart';
  4. import 'package:farm_tpf/data/repository/authentication_repository.dart';
  5. import 'package:meta/meta.dart';
  6. part 'authentication_event.dart';
  7. part 'authentication_state.dart';
  8. class AuthenticationBloc
  9. extends Bloc<AuthenticationEvent, AuthenticationState> {
  10. AuthenticationBloc(
  11. {@required AuthenticationRepository authenticationRepository})
  12. : assert(authenticationRepository != null),
  13. _authenticationRepository = authenticationRepository,
  14. super(const AuthenticationState.unknown()) {
  15. _authenticationStatusSubscription = _authenticationRepository.status.listen(
  16. (status) => add(AuthenticationStatusChanged(status)),
  17. );
  18. }
  19. final AuthenticationRepository _authenticationRepository;
  20. StreamSubscription<AuthenticationStatus> _authenticationStatusSubscription;
  21. @override
  22. Stream<AuthenticationState> mapEventToState(
  23. AuthenticationEvent event,
  24. ) async* {
  25. if (event is AuthenticationStatusChanged) {
  26. yield await _mapAuthenticationStatusChangedToState(event);
  27. } else if (event is AuthenticationLogoutRequested) {
  28. _authenticationRepository.logOut();
  29. }
  30. }
  31. @override
  32. Future<void> close() {
  33. _authenticationStatusSubscription?.cancel();
  34. _authenticationRepository.dispose();
  35. return super.close();
  36. }
  37. Future<AuthenticationState> _mapAuthenticationStatusChangedToState(
  38. AuthenticationStatusChanged event,
  39. ) async {
  40. switch (event.status) {
  41. case AuthenticationStatus.unauthenticated:
  42. return const AuthenticationState.unauthenticated();
  43. case AuthenticationStatus.authenticated:
  44. return AuthenticationState.authenticated();
  45. default:
  46. return const AuthenticationState.unknown();
  47. }
  48. }
  49. }