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.

50 lines
1.6KB

  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 extends Bloc<AuthenticationEvent, AuthenticationState> {
  9. AuthenticationBloc({required AuthenticationRepository repository})
  10. : _authenticationRepository = repository,
  11. super(const AuthenticationState.unknown()) {}
  12. final AuthenticationRepository _authenticationRepository;
  13. StreamSubscription<AuthenticationStatus>? _authenticationStatusSubscription;
  14. @override
  15. Stream<AuthenticationState> mapEventToState(
  16. AuthenticationEvent event,
  17. ) async* {
  18. if (event is AuthenticationStatusChanged) {
  19. yield await _mapAuthenticationStatusChangedToState(event);
  20. } else if (event is AuthenticationLogoutRequested) {
  21. _authenticationRepository.logOut();
  22. }
  23. }
  24. @override
  25. Future<void> close() {
  26. _authenticationStatusSubscription?.cancel();
  27. _authenticationRepository.dispose();
  28. return super.close();
  29. }
  30. Future<AuthenticationState> _mapAuthenticationStatusChangedToState(
  31. AuthenticationStatusChanged event,
  32. ) async {
  33. switch (event.status) {
  34. case AuthenticationStatus.unauthenticated:
  35. return const AuthenticationState.unauthenticated();
  36. case AuthenticationStatus.authenticated:
  37. return const AuthenticationState.authenticated();
  38. default:
  39. return const AuthenticationState.unknown();
  40. }
  41. }
  42. }