Search code examples
androidmvvmandroid-jetpack-composeviewmodeldagger-hilt

How to pass parameter to my hilt viewmodel from jetpack compose


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.


Solution

  • Assuming that you have followed the documentation for compose navigation, you can find your parameter here:

    @HiltViewModel
    class RouteDetailsViewModel @Inject constructor(
        private val getRouteByIdUC: GetRouteByIdUC,
        private val savedStateHandle: SavedStateHandle
    ): ViewModel() {
    
        private val routeId = savedStateHandle.get<String>("your-param-name") // for example String in my case
    }