20

How to pass parameter to viewmodel constructor using HiltViewModel library with jetpack compose My code:

@HiltViewModel
class GetPurchaseViewModel @Inject constructor(val id:Long) : ViewModel() {
    private val service= RestModule
    var state = MutableStateFlow<State>(State.START)

    init{
        get(id)
    }

    private fun get(id:Long){
        viewModelScope.launch {
            state.value = State.LOADING
            try {
                val users = withContext(Dispatchers.IO) {

                    service.getIntance().getPurchase(id)
                }

                state.value = State.SUCCESLISTPURCHASE(users)
            } catch (e: Exception) {
                state.value = State.FAILURE(message = e.localizedMessage!!)
            }
        }
    }

}

my call in my composable function :

val model:GetPurchaseViewModel=hiltViewModel(idUser)
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
Rafael Souza
  • 1,143
  • 2
  • 13
  • 29
  • 3
    Depending on where that id comes from, you could use the savedStateHandle in the viewmodel, it gets pre-populated with the navigation arguments if you use the navigation artifact. – Francesc Jan 05 '22 at 00:47
  • do you have any easy examples of doing this? or some site that explains – Rafael Souza Jan 05 '22 at 01:08
  • 6
    I just put together a quick sample here: https://github.com/fvilarino/Navigation-Sample – Francesc Jan 05 '22 at 01:44
  • Does this answer your question? [How to pass id and application to a viewModel/viewModelFactory in Jetpack Compose?](https://stackoverflow.com/questions/69145407/how-to-pass-id-and-application-to-a-viewmodel-viewmodelfactory-in-jetpack-compos) – Phil Dukhov Jan 05 '22 at 02:33
  • Does this answer your question? [How to use Hilt to inject a safe-args argument into a viewmodel?](https://stackoverflow.com/questions/67350331/how-to-use-hilt-to-inject-a-safe-args-argument-into-a-viewmodel) – Ayman Feb 22 '22 at 13:02
  • The short answer is if you place the arg in a NavHost argument, it will auto-magically pass to the SavedStateHandle - [see answer here](https://stackoverflow.com/a/73269361/1703677) – beyondtheteal Mar 09 '23 at 19:05

1 Answers1

1

I would recommend you to use @AssistedInject, here is official documentation

Also please take a look at this issue [AssistedInject] Integration with @HiltViewModel #2287

Yvgen
  • 2,036
  • 2
  • 23
  • 27