I'm using a Cubit-repository-datasource design separated by feature.
Title mostly says it all, but to extrapolate: I have an authentication Cubit. It is under the /authentication
feature. I have another feature, /posts
, that needs an access token from the /authentication
feature to send an API request. This token is provided to it from the widget tree (authentication cubit is provided from the top of the widget tree). When a method from /posts
's cubit is called: getPosts(int numOfPosts, String accessToken)
, it takes an access token from the provided widget tree's authentication cubit and passes it to the posts cubit. From here, it sends the request down to the repository layer, then to the data layer.
HOWEVER, what happens if the token is invalid? What happens if it has been tampered with? What happens if it's null? Then, I'd like the token to first be refreshed, and then to repeat the same call for posts using the refreshed access token. However, that "refresh the access token" method is inside the authentication cubit, not the posts cubit. How then should I call it? Can I call the refreshAccessToken()
method (inside the /authentication
feature's repository or data layer) from inside the repository or data layer of the /posts feature?
Is this sort of "crossing-feature" bad?
Thanks!
I second the comment made by @FabriBertani. The bloc/cubit shouldn't know anything about how to get the posts. It should just do getPosts(int numberOfPosts)
.
That method should e.g. come from an interface (abstract class in Dart) which in turn is implemented in a different layer (e.g. data/repository/service layer).
That implementation can then in turn handle what is needed to fetch the data from your API. It could e.g. have an authentication service injected to it from where it gets the token.