问题
what would it be the best practice about placing Presenters in a Scope?
Could we have Presenters on @Singleton or @AppScope without any problem?
Should they be placed in an @ActivityScope in order to destroy them each time the activity is destroyed?
回答1:
what would it be the best practice about placing Presenters in a Scope?
Usually a presenter should be in some scope. Not placing it in any scope will lead to problems, as every time you request a presenter it would create a new one.
Which scope you choose mostly depends on your programming style, but the most common would probably be @PerActivity
, as a scope that follows the lifecycle of the Activity. (the same way you can use something like @PerFragment
with Fragments and their lifecycle)
Could we have Presenters on @Singleton or @AppScope without any problem?
Yes and no. Longer living objects referencing shorter lived ones (e.g. a @Singleton
object that references an activity-lifecycled one) usually is not a good practice that might lead to memory leaks.
You can avoid these issues by properly adding / removing your shorter lived objects (e.g. add in onCreate
, remove in onDestroy
) or using WeakReference
.
Some programmers will keep their presenters as @Singleton
or in some similar fashion and swap views, but again this depends on how you prefer your code. It will work, but you must make sure what objects you reference and to clean up afterwards.
Should they be placed in an @ActivityScope in order to destroy them each time the activity is destroyed?
This is by far the easiest option, since you have no problem referencing the Activity or anything else that depends on it. You most likely won't have to worry about memory leaks or other issues this way.
In the end its your code and you have to do what works best for you.
来源:https://stackoverflow.com/questions/44438925/dagger-2-scopes-where-to-place-presenters