gpt4 book ai didi

android - 使用 Dagger 2 DI,替换构建组件上的子组件

转载 作者:行者123 更新时间:2023-11-30 01:08:32 30 4
gpt4 key购买 nike

我是 Dagger2 的新手,但我已经开始喜欢在我的项目中使用它的优势。我目前正在尝试了解自定义范围。

我有这个基本的应用程序设置:ApplicationComponentActivityComponentUserComponent。这就是我希望它们在我的应用程序中工作的方式

                  [-----------User scope-------------]
[ Activity scope ][ Activity scope ][ Activity scope ][ Activity scope ]
[-----------------------Aplication Scope (Singleton)-------------------]

在中间的两个 Activity 中,用户已登录。

我的依赖图如下所示:AplicationComponent <- ActivityComponent <- UserComponent

UserComponent 依赖于 ActivityComponent 来工作,ActivityComponent 依赖于 AplicationComponent

UserComponent 只是一个“专用”ActivityComponent,它还提供当前登录的用户。不需要用户的 Activity 将使用 ActivityComponent 注入(inject),需要用户注入(inject)的 Activity 将需要使用 UserComponent。希望它有意义。

当用户第一次登录时,我在当前 Activity 中创建一个UserComponent:

ActivtyComponent activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this)) //** here, 'this' is the current Activity
.applicationComponent(MyApplication.getApp(getActivity()).getAppComponent())
.build();

UserComponent userComponent = DaggerUserComponent.builder()
.activityComponent(activityComponent)
.build();

userComponent.inject(this);

//Store user component to be retrieved by other activities
MyApplication.getApp(getActivity()).storeUserComponent(userComponent);

这很好用。现在,假设我启动了一个 Activity 并尝试注入(inject)它的依赖项。这次容易多了,为此我已经存储了一个 UserComponent!我可以只用那个,对吧?:

MyApplication.getApp(getActivity()).getUserComponent().inject(this);

错了!...它会崩溃!因为该组件仍将之前的 Activity 存储在其 Activity 模块中(**参见上面的代码)

而且我不想创建另一个 UserComponent,那样会使作用域变得无用...所有提供的方法都将被再次调用,对吗?

我需要那个特定的组件,而不是一个新组件。但是我必须以某种方式将它的 ActivityComponent 换成一个新的,新的将在它的 activityModule 中传递这个 Activity ......这是我的问题:

这可能吗?我是否以正确的方式看待这个?我可以更改已构建组件中的子组件吗?

提前致谢

最佳答案

通常大多数教程显示它的方式是你有像 AppComponent <- UserComponent <- ActivityComponent 这样的依赖项。

组件只创建一次作用域对象,如果发生变化,您应该创建一个新组件。 dagger 2 中没有热插拔模块或对象,如果你仔细思考一下你就会明白为什么:
如果您提供依赖项 A,然后在任何地方都使用 A,然后用 NEW-A 替换 A 并从那时起开始使用 NEW-A...那是您可能想要避免的真的不一致状态。

一个组件应该存在于它各自的生命周期中。如果您的组件保留对 Activity 的引用,则应仅将其与此 Activity 一起使用,否则会导致内存泄漏(或像您这样的错误)。

如果您的用户组件依赖于应用程序,那么您可以将该组件存储在应用程序中而不会产生任何问题。然后,您的 Activity 只需创建自己的、范围内的组件——使用并依赖于应用程序或用户组件。

关于android - 使用 Dagger 2 DI,替换构建组件上的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38671711/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com