Search code examples
androidviewmodelandroid-jetpack-composedagger-hiltandroid-navigation-graph

How to get view model with hilt outside activity in jetpack compose


So I have a kotlin file named "ListScreen" (it's not a class! just a .kt file with composable functions) and I'm handling transactions with compose navigation graph system. Right now I'm trying to access my ViewModel which is indicated with @HiltViewModel from the "ListScreen" file. Apparently, in the past, there was a way to access ViewModels with hilt like this: viewModel: PokemonListViewModel = hiltNavGraphViewModels() but this isn't working right now. how can I do it?

here's my ViewModel class:

@HiltViewModel
class PokemonListViewModel @Inject constructor(
private val repository: PokemonRepository
) : ViewModel() {


fun calcDominantColor(
    drawable: Drawable,
    onFinish: (Color) -> Unit
) {
    val bmp = (drawable as BitmapDrawable).bitmap.copy(Bitmap.Config.ARGB_8888, true)

    Palette.from(bmp).generate { palette ->
        palette?.dominantSwatch?.rgb?.let {
            onFinish(Color(it))

        }

    }
}
}

and here's the block of code which isn't working:

 @Composable
fun PokedexEntry(
    entry: PokedexListEntry,
    navController: NavController,
    modifier: Modifier = Modifier,
    viewModel: PokemonListViewModel = hiltNavGraphViewModels()

) 

Solution

  • hiltNavGraphViewModels() is now depcecated. Use hiltViewModel() instead.

    From android documentation.

    Deprecated: Use hiltViewModel() instead.. Replace with: "hiltViewModel()".
    

    https://developer.android.com/reference/kotlin/androidx/hilt/navigation/compose/package-summary#hiltNavGraphViewModel()