androiddagger-2dagger-hilt

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


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)

Solution

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

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