https://kotlinlang.org logo
Title
d

Daniele Segato

11/26/2021, 1:06 PM
Can we exchange ideas about how to make `ViewModel`s independent of compose? I'm thinking specifically of
TextFieldValue
for forms. Say you need to control both the text and the selected state from the ViewModel. How do you handle this scenario?
a

Alex

11/29/2021, 9:45 AM
Create a TextFieldState containing StateFlows and put it into your ViewModel
this should provide a clear sepearation
d

Daniele Segato

11/29/2021, 11:04 AM
So basically have a remapping of TextFieldState into TextFieldValue by copying text and selection attributes and keeping previous composition ones? Not a big fan of that :-)
a

Alex

12/01/2021, 1:29 PM
Basically the ViewModel should not know what type of consumer there is (android textfield or compose TextField or whatever), so you should just keep the values that are needed for the viewmodels logic and provide callbacks too
so, no, not exactly what you wrote tbh 😄
d

Daniele Segato

12/01/2021, 2:52 PM
That's exactly what I wrote if i need to control both the selection and the text from the ViewModel
a

Alex

12/02/2021, 9:47 AM
Consider this:
class ThatViewModel: ViewModel(){
  val textFieldValue = MutableStateFlow("")

  fun onTextChange(text: String)
  fun onTextSelectionChange(selectedText: String)
}
Would this not make sense?
d

Daniele Segato

12/02/2021, 12:38 PM
For most situation, yes, it would. But i want to control the text selection too. And i would also like to control which is the focused field / be informed when the user change focus so that I can react appropriately. I consider these stuff state. And currently it's lot of work to create a compose Independent layer for them.
a

Ali Khaleqi Yekta

09/25/2022, 3:14 AM
@Daniele Segato I know this is old but, did you come to any conclusions? Anything that also suffices for having control over selection?
d

Daniele Segato

10/04/2022, 5:23 PM
@Ali Khaleqi Yekta the solution was quite simple when i just realized that compose had nothing to do with it. Just write your own data class to describe what the state should be (selection or whatever) and in the compose side use it as you use any other state.