https://kotlinlang.org logo
#compose
Title
# compose
m

Matti MK

11/17/2021, 11:52 AM
I’ve got a problem where my VM gets re-initialized when moving between composable screens. Not quite sure on how to go about fixing it. My VM is initialized by
Koin
as shown below.
Copy code
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module

actual val myScreenModule = module {
    viewModel { MyScreen() }
}
The VM itself extends
import androidx.lifecycle.ViewModel
class. And inside my
NavGraphBuilder.addMainGraph
block I instantiate the screen
Copy code
composable(MyScreen.route) {
        MyScreen(
            viewModel = get(),
        )
    }
Not quite sure how to go about things here: is this expected behaviour and I should store VM state inside or is there some other way that I could keep the state?
c

Csaba Kozák

11/17/2021, 12:00 PM
You should use the
getViewModel()
function. See here.
m

Matti MK

11/17/2021, 12:02 PM
Agh, damn. That solves it 😅
👌 1
Thanks a lot, this gave me a bunch of unnecessary headache 👍