You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the example below, the coroutineScope is created in the SomeScreen() context, and then it is used as a parameter for koin injection. Even though the same coroutineScope is used in all recompositions, rememberKoinInject() returns new instance of SomeViewModel every time. (model is not actually remembered)
@Composable
fun SomeScreen() {
val coroutineScope = rememberCoroutineScope()
val viewModel = rememberKoinInject<SomeViewModel> { parametersOf(coroutineScope) }
...
}
The (probable) cause:
coroutineScope parameter is wrapped into a lambda behind the scenes, and then then the newly created lambda is passed down the chain to composable remember method as a key for evaluation. The lambda is different each time so evaluation will be re-run reglardless if provided parameter is the same or not.
val viewModel = rememberKoinInject<SomeViewModel> { parametersOf(coroutineScope) }
is eqal to
val viewModel = rememberKoinInject<SomeViewModel>(parameters = { parametersOf(coroutineScope) }) //lambda!
The workaround:
As for now, the workaround is to remember the whole lambda with parameter, and pass the exact same lambda to rememberKoinInject function:
@Composable
fun SomeScreen() {
val coroutineScope = rememberCoroutineScope()
val parametersOf: () -> ParametersHolder = remember {
{ parametersOf(coroutineScope) }
}
val viewModel = rememberKoinInject<SomeViewModel>(parameters = parametersOf)
...
The fix
Providing a working solution that will utilize default rememberKoinInject syntax:
val viewModel = rememberKoinInject<SomeViewModel> { parametersOf(coroutineScope) }
The text was updated successfully, but these errors were encountered:
I think that is expected behavior, since the lambda refs to unstable vars (such as scope), that makes this lambda unstable as well, so the compiler will not remember lambda automatically.
In the example below, the
coroutineScope
is created in theSomeScreen()
context, and then it is used as a parameter for koin injection. Even though the samecoroutineScope
is used in all recompositions,rememberKoinInject()
returns new instance ofSomeViewModel
every time. (model is not actually remembered)coroutineScope
parameter is wrapped into a lambda behind the scenes, and then then the newly created lambda is passed down the chain to composableremember
method as a key for evaluation. The lambda is different each time so evaluation will be re-run reglardless if provided parameter is the same or not.As for now, the workaround is to remember the whole lambda with parameter, and pass the exact same lambda to
rememberKoinInject
function:Providing a working solution that will utilize default
rememberKoinInject
syntax:The text was updated successfully, but these errors were encountered: