https://kotlinlang.org logo
Title
k

KotlinLeaner

01/17/2023, 1:30 PM
Hi guys, I want to avoid multiple function call when
LaunchEffect
key triggers.
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.
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

Zach Klippenstein (he/him) [MOD]

01/18/2023, 4:24 PM
One of those things must be changing after composition. It would seem reasonable for uiState to change pretty frequently, based on its name.
k

KotlinLeaner

01/18/2023, 4:25 PM
So is there way we can handle ?
z

Zach Klippenstein (he/him) [MOD]

01/18/2023, 4:57 PM
Why is uiState a key to that effect at all? It’s not used by the effect
k

KotlinLeaner

01/18/2023, 4:58 PM
What do you mean by effect at all ?
z

Zach Klippenstein (he/him) [MOD]

01/18/2023, 5:17 PM
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

KotlinLeaner

01/18/2023, 6:04 PM
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

Zach Klippenstein (he/him) [MOD]

01/18/2023, 6:12 PM
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

KotlinLeaner

01/18/2023, 6:33 PM
Okk sure, thanks 👍