In the flutter_bloc
- Login✨ tutorial the AuthentificationRepository
streams an Authentification status like so :
Stream<AuthenticationStatus> get status async* {
await Future<void>.delayed(const Duration(seconds: 1));
yield AuthenticationStatus.unauthenticated;
yield* _controller.stream;
}
In my real app with a back-end I'd like to also Stream the AuthentificationStatus
in order to re-route the user out if his session is no longer valid
How would this implementation look like inside a real app ?
Would I have to query my API every second to implement a similar stream ?
I'm open to suggestion to implementing this re-routing behavior & streaming the AuthentificationStatus
CodePudding user response:
You should not interpret the use of the status
stream as some kind of placeholder for network access.
The idea behind repositories in those examples is, to provide common access to (domain) data across multiple business components (blocs or cubits) of your app.
Check out this article: https://verygood.ventures/blog/very-good-flutter-architecture by VGV for example.
Two separate blocs could use the AuthentificationRepository
to query information about whether a user is authenticated or not, by calling a function like getStatus
.
Here, the stream status
is useful if you want to notify blocs or cubits pro-actively about state changes, so that different parts of your application are able to react accordingly without having to call the repository themselves. This is what the status
stream is for in this case, regardless of how you obtain the "real" authentication status.
If you really want to "push" the information from your backend to your client, there are many ways to do this. But keep in mind, that the client may be offline and the information might not reach the client at all. You could use WebSockets, Polling (what you suggested), or Firebase Messaging, to name a few options.
Personally, I would rather try to access the backend and submit some kind of token with each call. If the request fails with HTTP status 401 or 403, I would let the AuthentificationRepository
know that the user is no longer authenticated. It will then inform subscribers of the status
stream.