stvn
06/30/2024, 7:40 PM// works
val startScanner = remember(viewModel) { { viewModel.startScanner() } }
i pass method like this to composable function, with remember
it works, but usually i have seen usages like viewModel::startScanner
, but when i tried it, it recomposes every time the parent composable recomposes, so it's not stable?swanti
06/30/2024, 9:01 PMLaunchedEffect
for what you want to achieve. Something like:
LaunchedEffect(Unit) { viewModel.startScanner() }
The LaunchedEffect is executed every time the key changes. So passing something like Unit
or true
means that the LaunchedEffect will only be executed when the view is initially composed.
You can also do things like:
LaunchedEffect(!viewModel.hasConnection.collectAsState().value) { viewModel.startScanner() }
to have the LaunchedEffect be executed every time a connection is lost. This example is probably better to handle directly in the ViewModel, but I just wanted to illustrate how the LaunchedEffect keys worklesincs
07/01/2024, 12:58 AMremember
to do this kind of logic? It is supposed to be used to cache values. Instead you should use effect apis such as SideEffect
and LaunchEffect
depending on your usage.
2. Function reference should be stable. You can reference this page to diagnose:https://developer.android.com/develop/ui/compose/performance/stability/diagnoseAlbert Chang
07/01/2024, 2:47 AMlesincs
07/01/2024, 8:36 AMthe function reference will be recreated on each recomposition, making the stability irrelevant,That's good to know. So seems trying to use function references for
ViewModel
requests does no good but just making code a bit neater?
And back to the original question, I just realized that stability is a term for recomposition, however for remember
keys, they are just compared by equals
. So if it did be called every time during every recomposition, the only reason would be it's has been regenerated every time?Albert Chang
07/01/2024, 8:45 AMtrying to use function references forRight.requests does no good but just making code a bit neaterViewModel
I just realized that stability is a term for recomposition, however forI don't really understand your question. Can you reword it?keys, they are just compared byremember
. So if it did be called every time during every recomposition, the only reason would be it's has been regenerated every time?equals
lesincs
07/01/2024, 8:59 AMremember(viewModel){...}
was being replaced to remember(viewModel::startScanner){...}
that's why I wrote the above.