Pavel Shorokhov
Pavel Shorokhov

Reputation: 4994

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.

Upvotes: 4

Views: 465

Answers (1)

Alektas
Alektas

Reputation: 656

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.

Upvotes: 1

Related Questions