42 lines
1.2 KiB
Dart
42 lines
1.2 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:bloc/bloc.dart';
|
|
import 'package:equatable/equatable.dart';
|
|
import 'package:user_repository/user_repository.dart';
|
|
|
|
part 'authentication_event.dart';
|
|
part 'authentication_state.dart';
|
|
|
|
class AuthenticationBloc
|
|
extends Bloc<AuthenticationEvent, AuthenticationState> {
|
|
final UserRepository userRepository;
|
|
late final StreamSubscription<MyUser?> _userSubscription;
|
|
|
|
AuthenticationBloc({required this.userRepository})
|
|
: super(const AuthenticationState.unknown()) {
|
|
_userSubscription = userRepository.user.listen((user) {
|
|
add(AuthenticationUserChanged(user));
|
|
});
|
|
|
|
on<AuthenticationUserChanged>((event, emit) {
|
|
if (event.user != null && event.user != MyUser.empty) {
|
|
emit(AuthenticationState.authenticated(event.user!));
|
|
} else {
|
|
emit(AuthenticationState.unauthenticated());
|
|
}
|
|
});
|
|
on<AuthenticationLogoutRequested>((event, emit) async {
|
|
try {
|
|
await userRepository.logOut();
|
|
} catch (_) {
|
|
// ignore errors here; stream will update state accordingly
|
|
}
|
|
});
|
|
}
|
|
@override
|
|
Future<void> close() {
|
|
_userSubscription.cancel();
|
|
return super.close();
|
|
}
|
|
}
|