简体   繁体   English

Android Hilt - 如何在片段之间共享依赖项?

[英]Android Hilt - How to share dependency between fragments?

How to share dependency between several specified fragments using Hilt/Dagger, but not all fragments?如何使用 Hilt/Dagger 在几个指定片段之间共享依赖关系,但不是所有片段?

I have single-activity-application.我有单一活动应用程序。 And have 3 fragments with creating one Entity.并有 3 个片段创建一个实体。 For example create user:例如创建用户:

... go to create user ...
1st fragment: enter phone -> put phone in interactor
2nd fragment: pick avatar -> put avatar in interactor
3rd fragment: enter name  -> put name in interactor + run
... success ...

And I want to start put data into interactor from 1st fragment, and finish put data on 3rd fragment and run interactor.我想从第一个片段开始将数据放入交互器,并完成将数据放入第三个片段并运行交互器。 And I expect that interactor will be destroyed when all these 3 fragments is destroyed.我预计当所有这 3 个片段都被销毁时交互器也会被销毁。

If I mark interactor in Dagger as @Singleton or @ActivityScoped - it will have problems with reuse.如果我将 Dagger 中的交互器标记为 @Singleton 或 @ActivityScoped - 它会出现重用问题。 Data in interactor will remain from previous starts.交互器中的数据将保留以前启动时的数据。 If I make it unscoped or @FragmentScoped - fragments will have 3 different interactors.如果我将其设为 unscoped 或 @FragmentScoped - 片段将有 3 个不同的交互器。

As one solution, you can put these 3 fragments in a Flow Fragment with its own navigation and DI graphs.作为一种解决方案,您可以将这 3 个片段放在具有自己的导航和 DI 图的 Flow Fragment 中。 The Flow DI container will share the Interactor between child fragments if you scope it (like @FlowScope). Flow DI 容器将在子片段之间共享交互器,如果你限定了它(比如@FlowScope)。 When user completes registration, the Flow Fragment will be popped up from app navigation graph, and the Interactor will be destroyed along with the Flow Fragment and its child fragments.当用户完成注册时,会从应用导航图中弹出 Flow Fragment,Interactor 将与 Flow Fragment 及其子 Fragment 一起销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM