Hi, I working on a KMP application. I want to shar...
# multiplatform
m
Hi, I working on a KMP application. I want to share the ViewModels for all the platforms (android, ios, desktop). I'm having problems editing a simple TextField on compose. My viewmodels store the inputed text on a MutableStateFlow, that is combined with other flows to produce the model to be displayed, transforming it to a StateFlow with stateIn in the viewModel, and then transforming it to a compose state with collectAsState. The problem is that I have a race condition, and when the user inputs the text the cursor makes strange behaviours. Does anyone have a solution, or an example with shared viewmodels with a textFiled (the samples I've seen do not contains texts fields, just data displaying).
j
I'm not sure if this is still behaving exactly like this (and I thought also read there were a few workarounds) but sounds like you might be running in to https://medium.com/androiddevelopers/effective-state-management-for-textfield-in-compose-d6e5b070fbe5
m
Yes, I've allready read this post. The problem is that they suggest to use MutableState, which is from compose and can't be used on iOs. There is another option mentioned by the following part:
f you would still rather use StateFlow to store state, make sure you’re collecting from the flow using the immediate dispatcher as opposed to the default dispatcher.
This solution requires deeper coroutines knowledge and might lead to issues:
* Since the collection is synchronous, it’s possible the UI is in a not-ready-to-operate-on state when it happens.
* Interferes with Compose’s threading and rendering phases, amongst other things, because it assumes that recomposition happens on the Main thread.
I've tried to do so, but with no success, that is what I was looking for an example.
I think that there is a problem with compose for desktop. If simplified to the following sample
Copy code
val coroutineScope = rememberCoroutineScope()
val textFlow = remember{ MutableStateFlow("") }
var textFlowState  = textFlow.collectAsState(textFlow.value, coroutineScope.coroutineContext)
TextField(
    value = textFlowState.value,
    onValueChange = { textFlow.value = it }
)
that works correctly on Android, but fails to work on Desktop (the cursor does not move corerctly and letters are reordered).