Reputation: 11
I am making an app that will have multiple basic number trackers (the numbers are saved in a database), Each tracker will have a button to add or reduce the number.
Is there a way to write a function in the viewmodel for adding or reducing the number that is reusable across all of the trackers?
Example code:
@Composable
fun TrackerScreen(viewModel: TrackerViewModel) {
val trackerUiState = viewModel.TrackerUiState.collectAsState()
Column{
Text("${trackerUiState.value.Tracker.valueOne}"
Row{
Button(onClick = { //function to increase valueOne by One })
{ Text("+1") }
Button(onClick = { //function to reduce valueOne by One })
Column{
Text("${trackerUiState.value.tracker.valueTwo}"
Row{
Button(onClick = { //function to increase valueTwo by One })
{ Text("+1") }
Button(onClick = { //function to reduce valueTwo by One })
// etc...
The viewmodel calls the state of the database with a dataclass (tracker) for each field
data class TrackerDetails(
val tracker: Tracker = Tracker()
)
data class Tracker(
val valueOne: Int = 0,
val valueTwo: Int = 0,
//etc...
)
I know I can set these all up as individual functions:
fun increaseTrackerOneByOne() {
viewModelScope.launch {
val trackerUpdate = trackerUiState.value.tracker.toTracker()
trackerRepository.updateTracker(trackerUpdate.copy(valueOne = trackerUpdate.valueOne + 1))
}
}
I was wondering if there was a way to set up this kind of function to work regardless of the tracker it's attached to?
(The app I'm working on will have roughly 20-30 of these trackers, if not more, so it would save me a lot of space and typing as well as following best practice of not repeating code..)
Upvotes: 0
Views: 53
Reputation: 11
I have found a workaround for now where I have:
This still requires a separate function line for each button and a composable for each button rather than being able to create them based off a list.forEach, but it's a start.
Upvotes: 0