How to create only one instance of ViewModel for m...
# android
i
How to create only one instance of ViewModel for my @Composable screen? Now every time when I call my @Composable, new ViewModel is created.
Copy code
@Composable
fun BankScreen() {
    val viewModel: BankViewModel = viewModel()
}
Tried to follow https://insert-koin.io/docs/reference/koin-android/compose/ but Android Studio throws weird error
l
You can obtain the viewModel within your activity so it's tied to the lifecycle of your activity instead of the shorter lifecycle of your composable
i
Thanks, I thought about it. I wonder can I create ViewModel for only first initialization of my @Composable
l
I'm not using jetpack's viewmodels but as far as I know, you have 2 options to achive this. 1. hoist the instantiation -> instantiate your viewmodel before you call your composable and pass the viewmodel to your composable 2. if you want to do something te first time, your composable enters you can achieve this with
DisposableEffect
but within this scope, you are not able to call @Composable functions, so I doubt you can instantite your viewmodel here.
Btw. there is a #compose channel where you can ask those questions 🙂
i
Ahh, thanks. I will ask
143 Views