【问题标题】:How to avoid Observable calling multiple times RxDart如何避免 Observable 多次调用 RxDart
【发布时间】:2020-01-09 00:20:51
【问题描述】:

我已经在我的登录屏幕上实现了 BLOC 模式。

下面的代码是按钮单击事件,当我第一次单击带有错误凭据的登录按钮时会发生这种情况上...

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();
          }
        }
      });
    }
  }
}

这是我的 BLOC 代码,我不知道我在哪里做错了。

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();

【问题讨论】:

    标签: flutter dart observable bloc rxdart


    【解决方案1】:

    问题是您每次调用_validateInputs 时都在注册一个监听器(通过调用listen)。您应该在 initState 中监听一次,或者尝试 Observable 中的 first 属性,该属性返回一个 Future。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      相关资源
      最近更新 更多