https://kotlinlang.org logo
#compose
Title
# compose
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:
Copy code
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.
@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.
3 Views