How do we inject runtime arguments into the viewmodel?
See original GitHub issueWhat if we wanted to have runtime arguments or other runtime arguments besides SavedStateHandle?
@AndroidEntryPoint
class TasksFragment : Fragment() {
private val viewModel by viewModels<TasksViewModel>()
private val args: TasksFragmentArgs by navArgs()
private val argToInject get() = args.userMessage
....
class TasksViewModel @ViewModelInject constructor(
private val tasksRepository: TasksRepository,
@Assisted argToInject:Int,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel()
@Assisted argToInject:Int
isn’t known to Dagger since we can’t annotate argToInject with @Assisted
, do we still have to use Assisted Inject by Square or there’s another way?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:36
- Comments:6 (2 by maintainers)
Top Results From Across the Web
How to pass runtime parameters to a ViewModel's constructor ...
I'm trying to figure out how to pass the itemId that I get from the ItemFragment's NavArgs to the ItemViewModel's constructor? Is there...
Read more >Inject “runtime” arguments into viewmodel using dagger2's ...
Our aim is to inject both the repository and the movie ID into our view model from the constructor using dagger. The issue...
Read more >Hilt: Inject Runtime parameters to ViewModels. - Carrion.dev
In this post we will learn how to use @AssistedInject from Dagger to inject runtime parameters to ViewModels with Hilt.
Read more >Passing Safe Args to your ViewModel with Hilt - ProAndroidDev
But what if we need to pass a Safe Args argument like a userId to our ViewModel? Without dependency injection, we would instantiate...
Read more >Parameter Injection for Android ViewModels | by Alex Frank
Injecting dependencies into our ViewModel is already good practice. It keeps the implementation flexible and easy to test. But what about parameters ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
If you primarily want access to the safe args in the view model, you might want to look at https://issuetracker.google.com/issues/136967621. Doesn’t seem to be getting much attention but that seems to be the obvious way to allow safe access from a SavedStateHandle.
Looking at the code it seems that
SavedStateHandle
uses the fragment’s arguments asdefaultArgs
so invoking theget
method on aSavedStateHandle
it’s possible to retrieve the values. It’s not documented so I am not sure if it’s a “feature” or it just works. @Chang-Eric what do you think?