Denki
Denki

Reputation: 363

Async method not being called

I want to separate a bloc logic into different methods, but for some reason when I do that it does not await for doLogIn(). I am not sure what I'm doing wrong.

@override
Stream<AuthState> mapEventToState(
  AuthState currentState,
  AuthEvent event,
) async* {
  if (event is LogIn) {
    await doLogIn();
  }
}

doLogIn() async* {
  try {
    final userId = await _authRepository.signIn("[email protected]", "xxxxxxxxxx");
    yield AuthLogInSuccess();
    final user = await _authRepository.getCurrentUser();
    yield AuthUserAvailable(firebaseUser: user);
  } catch (e) {
    print(e);
    yield AuthError();
  }
}

Upvotes: 2

Views: 358

Answers (1)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7856

Here is example how you can separate a bloc logic:

Clear bloc:

class LoginBloc extends Bloc<LoginEvent, LoginState> {

  @override
  LoginState get initialState => new Loading();


  @override
  Stream<LoginState> mapEventToState(
      LoginState currentState,
      LoginEvent event,
      ) async* {

    final newState = await event.getNewState(currentState);
    yield newState;
  }
}

States:

abstract class LoginState { }

class Loading extends LoginState { }

class LoginFailed extends LoginState {
  final String message;

  LoginFailed(this.message);
}

class LoginSuccessfulComplete extends LoginState  {
  final User user;

  LoginSuccessfulComplete(this.user);
}

And I propose to put transition logic into events:

abstract class LoginEvent {
  Future<LoginState> getNewState(LoginState state);
}

class AuthLoading extends LoginEvent {

  @override
  Future<LoginState> getNewState(LoginState state) async{    
    final _authService = new AuthService();
    final UserIndentity identity = await _authService.onLoad();

    if (identity.isEmpty) {
      return PhoneEnter();
    }

    final user = await _authService.login(identity);
    if (user == null){
      return LoginFailed('user not found');
    }
    return LoginSuccessfulComplete(user);
  }
}

Upvotes: 1

Related Questions