0

I want to make a UserScope with Dagger 2 that provides a User for several Activities. When the User log-in, Dagger inject the User to these activities, and once the User log-out, the instance must be null until the next log-in. this is what i did so far: the user scope:

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface UserScope {
}

the user component:

Dagger generate error saying that BaseActivity should be a module

@UserScope
@Subcomponent(
        modules = {
                UserModule.class,
                NetworkModule.class
        }
)
public interface UserComponent {

        UserComponent inject(BaseActivity activity);
}

and the UserModule

@Module
public class UserModule {

    private User user;

    public UserModule(User user) {
        this.user = user;
    }

    @Provides
    @UserScope
    FirebaseUser provideUser() {


  return user;
}

}

Should I make a Module activity for each activity that needs User ??

Fakher
  • 2,098
  • 3
  • 29
  • 45
  • 1
    Here is an article that might help: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ – David Medenjak Sep 14 '17 at 09:07
  • I saw this article, in fact each Activity is a self module, which generates a lot of classes. I am looking for a better solution – Fakher Sep 14 '17 at 09:08
  • 1
    You're using Dagger 2 wrong so please spend some more time reading the tutorials. Inject methods inside Components have to have return type `void`. So write `void inject(BaseActivity activity);` – David Rawson Sep 19 '17 at 00:51
  • @DavidRawson yes that's right, and i musn't put BaseActivity as parameter, It must the real activity cuz Dagger must know the target Activity in COmpile time – Fakher Sep 19 '17 at 07:52
  • There isn't really a 'better solution' than the one that frogermcs proposed I'm afraid. If you don't like writing classes I suppose you can choose not to use Dagger 2. In fact, it's probably overkill for a small project – David Rawson Sep 19 '17 at 09:30

0 Answers0