Search code examples
androidkotlindependency-injectionandroid-architecture-navigationandroid-safe-args

Android send ViewModel to Fragment via NavDirections arguement (Safe-Args)


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 ?


Solution

  • 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.