简体   繁体   中英

Android Hilt - How to share dependency between fragments?

How to share dependency between several specified fragments using Hilt/Dagger, but not all fragments?

I have single-activity-application. And have 3 fragments with creating one Entity. 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.

If I mark interactor in Dagger as @Singleton or @ActivityScoped - it will have problems with reuse. Data in interactor will remain from previous starts. If I make it unscoped or @FragmentScoped - fragments will have 3 different interactors.

As one solution, you can put these 3 fragments in a Flow Fragment with its own navigation and DI graphs. The Flow DI container will share the Interactor between child fragments if you scope it (like @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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