Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject viewModel to @Composable

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.

like image 341
Wafi_ck Avatar asked May 16 '21 16:05

Wafi_ck


2 Answers

Your viewModel gets destroyed whenever you destroy the composable, it can survive re-compositions but as soon as your composable gets destroyed it will be destroyed.

What you can do is create the viewModel in a scope that lives longer than the ProfileScreen composable and then pass the viewModel as parameter to it.

Something like this should work.

@Composable 
fun MainScreen() {
     val vModel : ProfileViewModel = viewModel()
     ....
     ProfileScreen(vModel)
}
like image 34
Omar Walid Avatar answered Oct 20 '22 05:10

Omar Walid


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

like image 138
jershell Avatar answered Oct 20 '22 06:10

jershell