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

1

6

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()

) 
Khorma answered 1/7, 2021 at 14:34 Comment(0)
T
9

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()

Taut answered 1/7, 2021 at 15:27 Comment(2)
Well that deprecation was really fast. Surprised me, even for googleDensify
Yeah since compose isn't stable yet, anything can happen.Taut

© 2022 - 2024 — McMap. All rights reserved.