Dagger 2示波器,在哪里放置演示者? [英] Dagger 2 Scopes, where to place Presenters?

查看:86
本文介绍了Dagger 2示波器,在哪里放置演示者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Presenters放置在示波器中的最佳做法是什么?

what would it be the best practice about placing Presenters in a Scope?

我们可以在@Singleton或@AppScope上使用演示者吗?

Could we have Presenters on @Singleton or @AppScope without any problem?

是否应将它们放置在@Act​​ivityScope中以在每次活动被销毁时将其销毁?

Should they be placed in an @ActivityScope in order to destroy them each time the activity is destroyed?

推荐答案


将演示者置于范围内的最佳做法是什么?

what would it be the best practice about placing Presenters in a Scope?

通常,演示者应该在 some 范围内。

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.

哪个范围,将其放置在任何范围内都会导致问题,因为每次您请求演示者时都会创建一个新的范围。选择主要取决于您的编程风格,但最常见的选择可能是 @PerActivity ,因为该范围遵循Activity的生命周期。 (以相同的方式,您可以将 @PerFragment 与片段及其生命周期一起使用)

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)


我们可以在@Singleton或@AppScope上使用演示者吗?

Could we have Presenters on @Singleton or @AppScope without any problem?

是,不是。寿命较长的对象引用寿命较短的对象(例如,引用活动生命周期对象的 @Singleton 对象)通常不是导致内存泄漏的好习惯。

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.

您可以通过正确添加/删除较短的生存对象来避免这些问题(例如,添加 onCreate ,删除 onDestroy )或使用 WeakReference

You can avoid these issues by properly adding / removing your shorter lived objects (e.g. add in onCreate, remove in onDestroy) or using WeakReference.

某些程序员会保留其演示者作为 @Singleton 或类似的方式和交换视图,但这又取决于您对代码的偏好。它将起作用,但是您必须确保引用并随后清除哪些对象。

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.


应将它们放在以下位置的@ActivityScope中为了在每次销毁活动时销毁它们?

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.

这篇关于Dagger 2示波器,在哪里放置演示者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆