How to avoid Observable calling multiple times RxDart

Issue

I have implemented BLOC pattern to my login screen.

The code below is button click event here what happens is when i click the Login button with wrong credentials first time it shows snackbar once, if i click the button again it show two times if i again click it shows three times & so on…

Future _validateInputs() async {
    final form = _loginKey.currentState;
    if (form.validate()) {
      print(_userIDController.text + _passwordController.text);
      bloc.validateLogin(_userIDController.text, _passwordController.text);
      bloc.loginDetails.listen((loginDetails){
        if(loginDetails != null) {
          if(loginDetails.loginStatus) {
            // Navigate to Home
            print("Login Sucess");
          } else {
            print(loginDetails.failureMessage);
            scaffoldKey.currentState.showSnackBar(SnackBar(
              content: Text('Invalid Username or Password'),
            ));
            //bloc.clear();
          }
        }
      });
    }
  }
}

This is my BLOC code i don’t know where i’m doing wrong.

class LoginBloc {
  final _repository = Repository();
  var _doLogin = PublishSubject<LoginModel>();

  Observable<LoginModel> get loginDetails => _doLogin.stream;

  validateLogin(String userName,String password) async {
    LoginModel itemModel = await _repository.doLogin(userName,password);
    _doLogin.sink.add(itemModel);
  }


  dispose() {
    _doLogin.close();
  }
}

final bloc = LoginBloc();

Solution

The problem is you are registering a listener (by calling listen) every time you call _validateInputs. You should listen once in the initState or try out the first property from Observable which returns a Future.

Answered By – Martyns

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.