https://kotlinlang.org logo
Title
l

Lucas

05/19/2023, 8:39 PM
Why doesnt this work? The ViewModel is being instantiated every render
@Composable
fun Composable(
) {
    val coroutineScope = rememberCoroutineScope()
    val viewModel: MyViewModel = koinInject { parametersOf(coroutineScope) }
}
koinInject has a remember so i dont understand why it doesnt work
@Composable
inline fun <reified T> koinInject(
    qualifier: Qualifier? = null,
    scope: Scope = LocalKoinScope.current,
    noinline parameters: ParametersDefinition? = null,
): T = rememberKoinInject(qualifier, scope, parameters)

/**
 * alias of koinInject()
 *
 * @see koinInject
 *
 * @author Arnaud Giuliani
 */
@Composable
inline fun <reified T> rememberKoinInject(
    qualifier: Qualifier? = null,
    scope: Scope = LocalKoinScope.current,
    noinline parameters: ParametersDefinition? = null,
): T = remember(qualifier, scope, parameters) {
    scope.get(qualifier, parameters)
}
I even tried remembering the parametersOf before, but it also didnt work
Ok this worked
val coroutineScope = rememberCoroutineScope()
val params = remember { { parametersOf(coroutineScope) } }
val viewModel: MyViewModel = koinInject(parameters = params)
The fact that ParametersDefinition is actually a typealias for () -> ParametersHolder made it harder to see
y

yschimke

05/19/2023, 10:19 PM
Doesn't this defeat the purpose of view model, if you inject something compose scoped like the coroutinescope? Will be recreated each time the activity gets recreated. And view models already have a viewmodelscope.
l

Lucas

05/19/2023, 11:13 PM
Compose desktop doesnt have the android viewmodel, so my viewmodel doesnt inherit anything (and therefore does not have a viewmodelscope), and there are no activies/events such as rotation in desktop, so my viewmodel will live as long as my composable
But yes, if i'm also targeting android i might make my viewmodels expect/actual, although i'm not sure screen rotation is an issue for my app
c

Colton Idle

05/20/2023, 2:08 PM
FWIW, screen rotation = configuration change and with compose it seems like its perfectly okay to opt out of all possible configuration changes (according to some people on the compose team) BUT you can still encounter configuration changes that you can't opt out of... like a wallpaper change. so you will eventually have to have some path forward for config changes.