Hi guys, I want to avoid multiple function call wh...
# compose
k
Hi guys, I want to avoid multiple function call when
LaunchEffect
key triggers.
Copy code
LaunchedEffect(key1 = isEnableState, key2 = viewModel.uiState) {
     viewModel.scanState(bluetoothAdapter)
}
when first composition
isEnableState
and
viewModel.uiState
both will trigger twice and call
viewModel.scanState(bluetoothAdapter)
.
isEnableState
is a
Boolean
type and
viewModel.uiState
is sealed class of UI types.
Copy code
var uiState by mutableStateOf<UIState>(UIState.Initial)
        private set 
var isEnableState by mutableStateOf(false)
        private set
So how can we handle idiomatic way to avoid duplicate calls? Thanks
z
One of those things must be changing after composition. It would seem reasonable for uiState to change pretty frequently, based on its name.
k
So is there way we can handle ?
z
Why is uiState a key to that effect at all? It’s not used by the effect
k
What do you mean by effect at all ?
z
The value of uiState is not read or used by the code inside the effect block. Neither is isEnabled, but it’s pretty common to key effects based on a flag like that. uiState is so vaguely named it’s hard to know what it actually means, and hard to understand why the effect needs to be restarted when it changes.
k
Yes, both keys are not using in the effect block. The function inside scanstate is changing according to the new state coming from uiState. The main problem is when initiall composition happens the launchefect block is using twice and I want to avoid that.
z
That seems like your ViewModel is leaking responsibility, if it requires the caller of scanState to know it depends on uiState. I would start by moving that dependency into scanState itself
k
Okk sure, thanks 👍