Luca Nicoletti
04/04/2023, 9:59 AMby remember
inside the composable
function? Without it, the edit text field value has a weird behaviour.
class MyState(val text: String)
class MyViewModel(initialState: MyState) {
internal val mState: MutableStateFlow<MyState> = MutableStateFlow(initialState)
val state: StateFlow<MyState> = mState.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = initialState,
)
}
@Composable
fun MyScreenState(state: MyState, onValueChange: (String) -> Unit) {
var rememberText by remember { mutableStateOf(state.text) }
OutlinedTextField(
value = rememberText,
onValueChange = { rememberText = it; onValueChange(it) }
)
}
remember
is an extra-step, forcing us to do things “twice” on the ValueChange callback as wellabbic
04/04/2023, 10:03 AMLuca Nicoletti
04/04/2023, 10:03 AMviewModel.state.collectAsState().value
MyScreenState
abbic
04/04/2023, 10:05 AMStylianos Gakis
04/04/2023, 10:58 AMrememberText
to the intial value of what the VM holds, and then keep a local state from that point on.
Can you show how you had it before you added the by
as you say? If you do that maybe it will show why it was having this weird behavior.Luca Nicoletti
04/04/2023, 11:00 AMremember
I had it inlined inside the TextField( value = state.text
Stylianos Gakis
04/04/2023, 11:10 AM