Inject viewModel to @Composable

Issue

I have viewModel for my ProfileScreen.

@Composable
fun ProfileScreen() {
    val viewModel: ProfileViewModel  viewModel()
    ...
}

Every time when I call ProfileScreen, new viewModel is created. How can I created only one viewModel instance for my ProfileScreen. I tried to inject viewModel following https://insert-koin.io/docs/reference/koin-android/compose/ but when I try

val viewModel: ProfileViewModel viewModel()

Android Studio throws error.

Solution

Or use remember() for save instance ViewModel between recompose calls

@Composable
fun ProfileScreen() {
    val viewModel  remember { ProfileViewModel() }
    ...
}

Also, rememberSaveable allows saving state(aka data class) between recreating of activity

Answered By – jershell

Leave a Comment