我正在尝试通过遵循此doc
来使用flutter_bloc实现bloc到bloc的通信所以我有2个块:AuthBloc和UserBloc。
UserBloc取决于AuthBloc,可以添加事件以响应AuthBloc的状态更改。例如,当用户成功登录后,应用程序应使用UserBloc加载用户数据。
这是我的AuthBloc:
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
final UserRepository userRepository;
AuthenticationBloc({@required this.userRepository});
@override
AuthenticationState get initialState => AuthenticationStateInitial();
@override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
if (event is AuthenticationStarted) {
bool hasLoggedIn = await userRepository.hasToken();
if (hasLoggedIn) {
yield AuthenticationSuccessState();
} else {
yield AuthenticationFailureState();
}
} else if (event is AuthenticationLoggedIn) {
yield AuthenticationLoadingState();
await userRepository.persistToken(event.token);
yield AuthenticationSuccessState();
} else if (event is AuthenticationLoggedOut) {
//...
}
}
}
这是我的UserBloc:
class UserBloc extends Bloc<UserEvent, UserState> {
final UserRepository userRepository;
final AuthenticationBloc authenticationBloc;
StreamSubscription authBlocSubscription;
UserBloc(this.userRepository, this.authenticationBloc) {
authBlocSubscription = authenticationBloc.listen((authState) {
print('auth state changed');
if (authState is AuthenticationSuccessState) {
print('auth state success');
//mapEventToState(LoadUserEvent());
}
});
}
@override
Future<void> close() {
authBlocSubscription.cancel();
return super.close();
}
@override
UserState get initialState => UserInitialState();
@override
Stream<UserState> mapEventToState(
UserEvent event,
) async* {
if (event is LoadUserEvent) {
yield UserLoadingState();
user = await userRepository.loadUser();
yield UserLoadedState(user);
}
}
}
但是问题在于订阅只调用了一次。因此,它只会打印一次auth state changed
,并且永远不会在身份验证状态更改时再次更新