How to pass parameter to my hilt viewmodel from jetpack compose

Viewed 51

I have a composable with viewmodel and I want to pass an id from the composable to the viewmodel.

My composable is:

@Composable
fun HttpRequestScreen(
    viewModel: HttpRequestViewModel = hiltViewModel(),
    id: String = EMPTYUUID,
    onClick: (String, String, Int) -> Unit // respond, request Function: 1 - send request, 2 - edit request
) {

I have the id from a different screen and I want to pass it to my Hilt viewmodel.

1 Answers

You will need to think in a Unidirectional Data Flow pattern, where events flow up and state flows down. For this, you need to expose some sort of state from your viewmodel that sends down the state of the request to the Composable as an observable state.

Your viewmodel could look like this.

class HttpRequestViewModel: ViewModel() {
private val _httpResponse = mutableStateOf("")
val httpResponse: State<String> = _httpResponse

fun onHttpRequest(requestUrl: String) {
    //Execute your logic
    val result = "result of your execution"
    _httpResponse.value = result
}

}

Then in your Composable, you can send events up by calling the ViewModel function on the button click like so

@Composable fun HttpRequestScreen(viewModel: HttpRequestViewModel) { val state by viewModel.httpResponse var userInput = remember { TextFieldValue("") }

Column {
    Text(text = "Http Response = $state")
}

BasicTextField(value = userInput, onValueChange = {
    userInput = it
})

Button(onClick = { viewModel.onHttpRequest(userInput.text) }) {
    Text(text = "Make Request")
}

}

I hope that points you in the right direction. Good luck.

Related