Created
August 4, 2019 18:48
-
-
Save felangel/953f7c5a6f9e7e091d43d951ac4ef951 to your computer and use it in GitHub Desktop.
[flutter_firestore_todos] authentication bloc
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'; | |
import 'package:user_repository/user_repository.dart'; | |
import 'package:flutter_firestore_todos/blocs/authentication_bloc/bloc.dart'; | |
class AuthenticationBloc | |
extends Bloc<AuthenticationEvent, AuthenticationState> { | |
final UserRepository _userRepository; | |
AuthenticationBloc({@required UserRepository userRepository}) | |
: assert(userRepository != null), | |
_userRepository = userRepository; | |
@override | |
AuthenticationState get initialState => Uninitialized(); | |
@override | |
Stream<AuthenticationState> mapEventToState( | |
AuthenticationEvent event, | |
) async* { | |
if (event is AppStarted) { | |
yield* _mapAppStartedToState(); | |
} | |
} | |
Stream<AuthenticationState> _mapAppStartedToState() async* { | |
try { | |
final isSignedIn = await _userRepository.isAuthenticated(); | |
if (!isSignedIn) { | |
await _userRepository.authenticate(); | |
} | |
final userId = await _userRepository.getUserId(); | |
yield Authenticated(userId); | |
} catch (_) { | |
yield Unauthenticated(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment