Compose needs a value for all its state-holders, b...
# compose
k
Compose needs a value for all its state-holders, but that value could be
null
. So something like this will work when you need a state, but don’t have the value at the time it’s created:
mutableStateOf<String?>(null)
Thread in Slack Conversation
Actually I am doing to make UI state management. Something like this
Copy code
sealed class BluetoothConnectionUIState {
    object Initial : BluetoothConnectionUIState()
    data class ScanningDevice(val storedDevice: SnapshotStateList<BluetoothDevice>? = null) : BluetoothConnectionUIState()
}
Actually I don't want to use
Initial
child in
when
statement.
Copy code
var uiState by mutableStateOf<BluetoothConnectionUIState>(BluetoothConnectionUIState.Initial)
    private set
Use of
when
statment in compose function
Copy code
when (uiState) {
    is BluetoothConnectionUIState.ScanningDevice -> {
        BluetoothPairContent()
    }
    BluetoothConnectionUIState.Initial -> {}
}
In
when
statement
Initial
child looks very ugly. So Is there a way to solve this problem?
p
If you find something let me know, I got a lot of code like that, ignoring the initial state
k
I don't have anything, if I find then I'll share with you in the thread.
p
I was kinda sarcastic, it seems to be a principle in the Reactive State world. The state has to have an initial value. But thanks
k
Oh ok, Thanks 🙏
c
Yes, in general, things in compose require some kind of initial value, it can’t simply be “absent”. You must acknowledge that the “value” should be before you actually set it, because Compose is potentially going to be trying to read that value before you even get a chance to set it in your code. The only way for Compose to be able know it will have a value available is if an initial value is required at the point that you call
mutableStateOf()
. And to this specific snippet, I wouldn’t call the
Initial
state a “throwaway value”, since it communicates valuable information, both to you, the programmer, and to the end-user. Especially if it takes time to connect to the Bluetooth device, your app might be left in that
Initial
state for a while, and you should display an appropriate message to the user during that time like “Attempting to connect”
k
That's great information. Thanks a lot for your guidance. I'll create a mind for using this kind of state.