我正在 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”,正如您所见,它是在构造函数之后定义的,与 streamsubscription 实例位于同一块中。我的代码可以工作并且这些事件会触发,但是由于这种新结构,我的 close 方法现在位于底部。谁能告诉我这个方法是否会被调用?
我已经在其中放置了打印语句,但它们似乎永远不会打印,但即使在以前的版本中,close() 中的打印语句也不会打印。有人知道在这个新的代码结构中是否会调用 close() 吗?