1

TL;DR: How to share data in a single flow using Dagger/Hilt Component but not shared view model?


I am trying to adopt the approach shown in Android docs, which uses Manual Dependency Injection to Dagger-Hilt Dependency Injection, using MVVM-Repository pattern.

Here is login flow of my app: iamge

I have 2 fragments:

  • UsernameFragment - it uses UserNameViewModel,
  • PasswordFragment - it uses PasswordViewModel.

I know that data between them could be shared by:

  • shared view model,
  • parent activity (a bit obsolete, probably).

However, using shared view model would mean tightly coupling those 2 fragments. (Let's imagine that I would use those 2 fragments again but in Registration Flow, where some additional screens were added - eg. PersonalInfoFragment. So I decided to have independent view model for each of them).

However if, you read Google docs linked above, you will notice that they use something like loginData object in their "Login container". It's use is clear for me in that case.

However, when they explain the same example using Dagger2, they silently drop this concept of shared loginData across the flow in the "Login container" (LoginComponent in that case).

I would be gratful if somebody help me, how to achieve the same goal (shared userData in "Login container") shown in ManualDI, but using Hilt or Dagger.

PS.Using Android NavigationUI I created a nested graph - which takes just that 2 fragments, so I am ensured, that using view models scoped to the graph would ensure me that every time user enters this login flow, the view models are "clean" (recreated). However it does not solve the problem of shared resource in "Login container"

Edit Fixed one edit text name ("Password") in attached picture.

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
PGliw
  • 311
  • 4
  • 9
  • What I usually do is, ditch the VMF and directly inject the repository in the VM using DI. For all the actions like registration, login, fetch details of a user, or any other related query is directly handled by the repository. From the image above you can see that at the end of the flow it is handled by repository only. The idea of DI is providing the dependencies to the class and VMF is used to do it for the VM. – Abhishek Saxena Aug 10 '20 at 14:17
  • Thank you, actually after spending some time on it I also decided to use shared repository between those fragments and just inject it to viewmodels (used Hilt's @ViewModelInject annotation). – PGliw Aug 10 '20 at 21:01

0 Answers0