1

I have an app with the following architecture:

  • Navigator is a custom class that holds the NavController
  • Cooridnator holds the Navigator
  • Cooridnator tells the Navigator to "start" the framgent and passes the ViewModel to it
  • Navigator asks NavController to navigateTo a NavDirections and provides the required arguments (using Safe-Args)

Now the issue here is that if I want to send the ViewModel as argument, it needs to be Parcelable and all of its underlying classes as well (which would make most of my code Parcelable, and that's not really needed).

So is there a way to do this without making everything Parcelable or using Dagger ? (Don't like Dagger as it adds too much complexity to the code...)

I would be okay with having a lateinit field in the Fragment and setting it manually but can't seem to access the Fragment from NavDirections

Any idea on how I could do this ?

Moumou
  • 1,513
  • 2
  • 18
  • 41

1 Answers1

1

First of all: what you are passing in safe args is "data" while your viewmodel is logic. Which means your data can change over the time (one of examples would be to become outdated) but as long as viewmodel is unchanged, it's logic would stay. Thus passing viewmodel itself does not make sense to me - best you can is to pass its snapshot of state, but I doubt that's what you want.

So yes, you should be using DI and there are alternatives to dagger complexity. You can experiment with koin (because I see kotlin in your tags list), some basic outline of what it can is here https://shorturl.at/bflFL (medium). You can also experiment with Hilt as what appears to be simplified alternative to Dagger, for android world.

ror
  • 3,295
  • 1
  • 19
  • 27
  • Oh right did miss that part about safe args...(am kind of new to Android and Kotlin). Thanks I'll check out koin ! Just to be sure, there is no way to pass the viewModel to the Fragment by having a public property for example ? – Moumou Jun 29 '20 at 03:57
  • You can of course do that, but from within - because fragment has its own lifecycle. More here https://developer.android.com/reference/android/arch/lifecycle/ViewModel – ror Jun 29 '20 at 04:29
  • But we don't have access to the fragment when using the NavController/NavDirections so how would you do that ? – Moumou Jun 29 '20 at 05:35
  • I ended up using Koin, wayyyy easier than Dagger to understand and use ! – Moumou Jun 29 '20 at 06:41