androiddependency-injectiondagger-2custom-scope

Can Dagger 2 have scopes shorter than an Activity life?


I've been looking at Custom Scopes in Dagger 2 (this and this are the ones i'm trying to base my code in), and there's one thing that i still can't seem to understand, i see that you can create a component with a custom scope and then all the provides form the modules contained by that component will be either the same scope as the component (singleton in the component) or un-scoped which will return new instances every time you get one.

But, the thing i still don't get is, if you have a User scope, and then you have some modules tied to that scope, let say that your network component is tied to it, so that the network calls use the current user information, if you sign-out the user (or sign in the user) mid Activity life cycle, will it change the object references that you currently have marked as @Inject? or whatever instance you got when you called .inject(this) in the activity onCreate method? Or you should call inject one more time in order to get the references mapped again?

Any help on this matter is highly appreciated :)


Solution

  • tl;dr You have to manage everything yourself. There is no refresh, you have to recreate or at least reload parts of your activity.

    Scopes provide some compile time information and help you to keep your code "readable". To actually swap components, this you will have to do yourself. And yes, you have to build your design around this, that depending components get recreated accordingly.

    If the user logs in / out you will have to create a new UserModule and component referencing the new user, supplying logged in / out objects. This is the new component you need to reference for all future components depending on it.

    @Inject annotated fields will not refresh automatically, albeit you can just inject a second time to the same fields, the objects will just be overwritten.

    In the second link you provided they actually do implement some sort of swapping the user information. This is done by keeping the UserComponent in the application class.