【问题标题】:Flutter. Will this streamsubscription get cancelled?扑。这个流订阅会被取消吗?
【发布时间】:2021-12-04 00:54:33
【问题描述】:

我正在 Flutter 中开发一个应用程序,在一个实例中,使用流订阅。我对内存泄漏有些担心,因为我不确定我的 close() 方法是否会被调用。

以前这不是问题,但由于更新了flutter_bloc,文件的结构发生了变化。

以前我的代码是这样的:

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository _authRepository;
  late StreamSubscription<auth.User?> _userSubscription;

  AuthBloc({
    required AuthRepository authRepository,
  })  : _authRepository = authRepository,
        super(AuthState.unknown()) {
    _userSubscription =
        _authRepository.user.listen((user) => add(AuthUserChanged(user: user)));
  }

  @override
  Future<void> close() {
    _userSubscription.cancel();
    return super.close();
  }

  @override
  Stream<AuthState> mapEventToState(AuthEvent event) async* {

您可以看到 mapEventToState 的开头位于构造函数的右括号之后。

目前,随着flutter_bloc 7.3的更新,我的代码如下所示:

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository _authRepository;
  late StreamSubscription<auth.User?> _userSubscription;
  AuthBloc({
    required ...,
  })  : _authRepository = ...,
        super(...) {

    _userSubscription =
        _authRepository.user.listen((user) => add(AuthUserChanged(user: user)));

    on<AuthUserChanged>((event, emit) {
      event.user != null
          ? emit(AuthState.authenticated(user: event.user!))
          : emit(AuthState.unauthenticated());
    });
    on<AuthLogoutRequested>((event, emit) async {
      await _authRepository.logOut();
    });
  }

  @override
  Future<void> close() {
    _userSubscription.cancel();
    return super.close();
  }
}

mapEventToState 被替换为“on”,正如您所见,它是在与流订阅实例相同的块中的构造函数之后定义的。我的代码可以工作并且这些事件会触发,但是由于这种新结构,我的 close 方法现在位于底部。谁能告诉我这个方法是否会被调用?

我已经在其中放置了打印语句,但它们似乎永远不会打印,但即使在以前的版本中,close() 中的打印语句也不会打印。有人知道在这个新的代码结构中是否会调用 close() 吗?

【问题讨论】:

    标签: flutter dart flutter-bloc dart-stream


    【解决方案1】:

    实际上,流订阅必须在 BloC 的更新版本上运行。查看更多关于https://github.com/felangel/bloc/issues/2890

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2020-04-07
    • 2016-07-12
    • 2021-10-31
    • 2021-02-24
    • 2021-08-08
    相关资源
    最近更新 更多