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.

54 lines
1.7KB

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