Dart Streams阻止

时间:2018-10-23 17:15:33

标签: stream dart

我正在为Futter应用程序使用BLoC模式,但是我无法让两个监听器都能正常工作。 如果我在loggedIn.listen()之前叫register.listen(),则register.listen()将不再起作用,反之亦然。

AuthBloc({this.authService}) {
    Stream<CrendentialsDetail> detailStream = Observable.combineLatest2(
      emailStream,
      passwordStream,
      (email, password) {
        return CrendentialsDetail(email: email, password: password);
      },
    );

    Stream<AuthResponse> loggedIn ... code ...

    Stream<RegisterResponse> register ... code ...

    register.listen((RegisterResponse res) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(res.message),
        ),
      );
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(error.message),
        ),
      );
    });

    loggedIn.listen((AuthResponse user) {
      currentUserSubject.add(user);
      _goToHome();
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(error.message),
        ),
      );
    });
  }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

这是我现在正在使用的解决方案。有人可以向我解释为什么有效,而我的问题却没有吗?

AuthBloc({this.authService}) {
    Observable(loginSubject.stream).withLatestFrom(
        Observable.combineLatest2(
          emailStream,
          passwordStream,
          (email, password) {
            return CrendentialsDetail(email: email, password: password);
          },
        ), (_, d) {
      return d;
    }).flatMap((d) {
      return Observable.fromFuture(authService.loginUser(d)).doOnListen(() {
        loadingSubject.add(true);
      }).doOnDone(() {
        loadingSubject.add(false);
      });
    }).listen((AuthResponse user) {
      currentUserSubject.add(user);
      _goToHome();
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(error.message),
        ),
      );
    });

    Observable(signUpSubject.stream).withLatestFrom(
        Observable.combineLatest2(
          emailStream,
          passwordStream,
          (email, password) {
            return CrendentialsDetail(email: email, password: password);
          },
        ), (_, d) {
      return d;
    }).flatMap((d) {
      return Observable.fromFuture(authService.register(d)).doOnListen(() {
        loadingSubject.add(true);
      }).doOnDone(() {
        loadingSubject.add(false);
      });
    }).listen((RegisterResponse res) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(res.message),
        ),
      );
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(
        new SnackBar(
          content: new Text(error.message),
        ),
      );
    });
  }