```// works val startScanner = remember(viewModel)...
# compose
s
Copy code
// 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?
s
I would usually use a
LaunchedEffect
for what you want to achieve. Something like:
Copy code
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 work
l
1. Why use
remember
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/diagnose
a
Function types are always stable, but if the containing class of a function reference is unstable, the function reference will be recreated on each recomposition, making the stability irrelevant, and view model classes are most likely unstable. In earlier versions function references were never recreated, but that’s actually not the intended behavior and has been fixed. If you don’t want the reference to be recreated, just enable strong skipping mode.
l
the 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?
a
trying to use function references for
ViewModel
requests does no good but just making code a bit neater
Right.
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?
I don't really understand your question. Can you reword it?
l
Sorry, I kind of misunderstood the original post. I thought
remember(viewModel){...}
was being replaced to
remember(viewModel::startScanner){...}
that's why I wrote the above.