android10 / Android-CleanArchitecture

This is a sample app that is part of a series of blog posts I have written about how to architect an android application using Uncle Bob's clean architecture approach.
Apache License 2.0
15.51k stars 3.32k forks source link

Should repositories know about authenticated user? #267

Open mr746866 opened 6 years ago

mr746866 commented 6 years ago

In my project, I need to fetch some data related to the authenticated user, and for that I need the userId of the user. I have an AuthManager class that gives me the userId of the authenticated user. I am confused whether to add this AuthManager class as a member of my UserRepository implementation, or just get the userId from AuthManager outside the repository and provide it when needed. Basically I have 2 options.

Option 1: Add AuthManager as a member to the UserRepository implementation. UserRepository will contain functions like getAuthenticatedUserFirstName(), getAuthenticatedUserLastName() etc. In the implementations of these functions use the AuthManager to get the necessary userId internally.

Option 2: Leave out AuthManager from the repository. UserRepository will contain functions like getFirstName(String userId), getLastName(String userId) etc. When calling these functions, use the AuthManager to get the required userId parameter.

Looking for feedback and suggestions.

mr746866 commented 6 years ago

@android10 Can you please shed some light on this?

crjacinro commented 6 years ago

Option 2 would be better. Not only it makes your functions generic (and reusable, when using different id as parameters), it also separates the concern. AuthManager is a "Manager" and not a repository. You may create something like SessionRepository to store session related data. and you can use that repository in the use case

alexwhb commented 6 years ago

@mr746866 Your other option is to create a custom scope... I call this my session scope, and in that scope I have my user model as a provided model, so I can inject it anywhere in my data layer which gives me acess to my userID and such, and as long as your data layer objects are scoped in the session graph they'll be able to inject the user modle... or you could even do @Named("userId") @Provides String userId or something to that effect.