简体   繁体   中英

Flutter. Will this streamsubscription get cancelled?

I am developing an application in Flutter and in one instance, using a stream subcscription. I have some concerns about memory leaks, as I am not sure if my close() method will ever get called.

Previously this wasn't a concern, but due to an update to flutter_bloc, the structure of a file has been changed.

Previously my code looked like this:

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* {

You can see the beginning of mapEventToState comes after the closing brackets of the constructor.

Currently, with the update to flutter_bloc 7.3, my code looks like this:

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 was replaced with "on", and as you can see it is defined after the constructor in the same block as the streamsubscription instantiaion. My code works and these events fire, but my close method is at the bottom now due to this new structure. Can anybody tell me if this method will ever get called?

I've put print statements inside of it and they never seem to print, but even in the previous version print statements inside of close() would not print. Does anybody know if close() will get called in this new code structure?

Actually, stream subscription must be working on the updated version of BloC. See more on https://github.com/felangel/bloc/issues/2890

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM