如果所有人都可以与SingletonComponent一起使用,为什么还要使用Android刀片使用不同的范围

发布于 2025-01-19 18:44:40 字数 260 浏览 0 评论 0原文

要添加 Hilt 模块,您需要执行以下操作:

@Module
@InstallIn(SingletonComponent::class)
abstract class MyModule{
...
}

有不同的范围,例如 ActivityComponent、ViewModelComponent 等,但我不清楚何时需要使用与 SingletonComponent 不同的范围,毕竟这涵盖了所有内容并且始终有效。这只是遵循封装的良好实践的问题吗?

To add a Hilt module you need to do this:

@Module
@InstallIn(SingletonComponent::class)
abstract class MyModule{
...
}

There are different scopes such as ActivityComponent, ViewModelComponent, etc, but it's not clear to me when would I need to use one different from SingletonComponent, after all this covers everything and always work. Is it just a matter of following good practices as with encapsulation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

破晓 2025-01-26 18:44:40

这是因为您注射对象的生命周期或范围。例如,如果设置模块的范围片段,则每次打开该对象的新实例时,都会创建该对象的新实例,并有资格在破坏片段时收集垃圾。您将不会在不再需要的内存中具有对象,有时您可能需要将对象的新实例复位而不是具有单胎对象。

It's because of lifecycle or scope of your injected objects. If you set your module's scope Fragment for instance, every time you open that Fragment new instance of that object will be created and will be eligible to be garbage collected when your fragment is destroyed. You won't have objects in memory that are not needed anymore and sometimes you might need new instance of your objects with their parameters reset instead of having Singleton objects.

醉南桥 2025-01-26 18:44:40

它归结为您的依赖性用例。范围是绑定图表中对象的寿命的一种方法。一些用例要求您的对象在容器(组件)寿命时生存。话虽如此,封盖对象寿命也是有益的内存,为什么您会将对象保留在applicationComponent中,该对象将通过应用程序生命周期生存,但是您只需要在应用程序的后期就需要它说一个片段,后来显示的片段。

某些用例要求您每次显示特定屏幕以具有正确的状态时具有新的对象实例。

It boils down to the use cases of your dependencies. Scopes are a way to bound the lifespan of an object in your graph. Some use cases require your object live while their container (component) lives. That being said, capping object life is also beneficial memory-wise, why would you keep an object in ApplicationComponent that will live through out application lifecycle, but you only need it in late stage of your app, let's say a Fragment that is shown later down the line.

Some use cases require you having fresh instance of a object each time a particular screen is shown in order to have correct state.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文