Skip to content

Instantly share code, notes, and snippets.

@YohannesTz
Created September 21, 2023 18:57
Show Gist options
  • Save YohannesTz/d24e1064ecdb72a669c78730176a37f6 to your computer and use it in GitHub Desktop.
Save YohannesTz/d24e1064ecdb72a669c78730176a37f6 to your computer and use it in GitHub Desktop.
Todo app fix
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ToDoAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val state by viewModel.state
TodoScreen(state = state, onEvents = viewModel::onEvent)
}
}
}
}
package com.app.todo
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class TodoMainViewModel(
private val dao: TodoDAO
) : ViewModel() {
/*private val _todoList = MutableStateFlow(dao.showAllTodos())
private val _state = mutableStateFlow(TodoState())
val state = combine(_state, _todoList){
state, todoList ->
state.copy(
todos = todoList
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), TodoState())*/
private val _state = mutableStateOf(TodoState())
val state: State<TodoState> = _state
init {
getTodos()
}
private fun getTodos() {
var savedTodos = emptyList<TodoData>()
viewModelScope.launch {
savedTodos = dao.showAllTodos()
}
_state.value = state.value.copy(
title = "",
description = "",
isAddingTodo = false,
todos = state.value.todos + savedTodos
)
}
fun onEvent(event: TodoEvents) {
when (event) {
is TodoEvents.SetDescription -> {
_state.value = state.value.copy(
description = event.setDescription
)
}
is TodoEvents.SetTitle -> {
_state.value = state.value.copy(
title = event.setTitle
)
}
is TodoEvents.DeleteTodo -> {
viewModelScope.launch {
dao.deleteTodoList(event.todo)
}
}
TodoEvents.SaveTodo -> {
val title = state.value.title
val description = state.value.description
if (title.isBlank() || description.isBlank()) return
val todo = TodoData(
title = title,
description = description
)
viewModelScope.launch {
dao.updateTodoList(todo)
}
_state.value = state.value.copy(
title = "",
description = "",
isAddingTodo = false,
todos = state.value.todos + todo
)
}
TodoEvents.HideDialog -> {
_state.value = state.value.copy(
isAddingTodo = false
)
}
TodoEvents.ShowDialog -> {
_state.value = state.value.copy(
isAddingTodo = true
)
}
}
}
}
// comment onEvents on line 90
confirmButton = {
//onEvents(TodoEvents.ShowDialog)
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment