Dagger 2 Scopes, where to place Presenters?

放肆的年华 提交于 2019-12-07 00:08:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!