I have a form UI written in Compose, the user can ...
# compose
j
I have a form UI written in Compose, the user can click a Create button that triggers an object creation that will be stored in a DB. Initially I was constructing the object in the Compose callback for the Create button, but I believe that's something the UI shouldn't be doing, so I moved the logic to the ViewModel, but then I ended up with a function with a lot of parameters, is there a better way to do this? I was thinking of using a state holder that's updated whenever the fields in the form are updated, so when the Create button is clicked I take the data from the state holder and I don't need to pass several parameters to the ViewModel function, but that would require hoisting the state of the TextFields, which I'm not sure if it's desired
b
Sounds to me like you are on the right path. You get a couple of benefits by keeping the state for each form field in the ViewModel. First, as you have discovered, it will allow you to simplify your “button click callback” to not have to pass all that data. Additionally, If the state for the form fields is kept in the viewmodel, you don’t have to worry (as much) about losing that state (due to re-compositions, or configuration changes, or process death, etc). When the user returns to the app, the state is read from the ViewModel (which did not die) and the form data they entered is still there waiting for them.
Initially I was constructing the object in the Compose callback for the Create button, but I believe that’s something the UI shouldn’t be doing
That is correct. I would think of it this way … when the user clicks the button, the UI should not have to know “oh, they clicked the button, the app is going to need all this data and use it to create a new object X, so I’ll collect it and create the object” … The UI shouldn’t know any of that. The UI shouldn’t even know what the button is for or that there is any other data at all. All the UI should know is … “the user clicked the button, so I’ll inform the app (i.e. the ViewModel) that it was clicked, and the app can do whatever it wants in response”. Then, the responsibility falls on the ViewModel to gather up all the relevant data and do something with it (probably pass it along to another layer/class that contains the business logic to use the data in a meaningful way) when it’s “onButtonClicked” function is called.
j
Makes a lot of sense, it even facilitates process death recovery if the data is kept in the ViewModel. Thanks!