..
This commit is contained in:
parent
e3bc4f6b74
commit
f246d2efbb
@ -1,2 +1,61 @@
|
|||||||
package at.xaxa.ledger.ui.category
|
package at.xaxa.ledger.ui.category
|
||||||
|
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.lifecycle.SavedStateHandle
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import at.xaxa.ledger.data.Entry
|
||||||
|
import at.xaxa.ledger.data.EntryRepository
|
||||||
|
import at.xaxa.ledger.data.db.Category.CategoryEntity
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
|
||||||
|
data class CategoryListUIState(val categories: Flow<List<CategoryEntity>> = flowOf(emptyList()))
|
||||||
|
|
||||||
|
|
||||||
|
class CategoryViewModel(
|
||||||
|
private val savedStateHandle: SavedStateHandle,
|
||||||
|
private val repository: EntryRepository
|
||||||
|
) : ViewModel() {
|
||||||
|
var categoryUiState by mutableStateOf(CategoryListUIState())
|
||||||
|
|
||||||
|
init {
|
||||||
|
getAllCategories()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addCategory(category: CategoryEntity) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val categoryEntity = CategoryEntity(
|
||||||
|
_id = category._id,
|
||||||
|
categoryName = category.categoryName,
|
||||||
|
icon = category.icon,
|
||||||
|
)
|
||||||
|
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
repository.insertCategory(categoryEntity) // Add game to the database
|
||||||
|
}
|
||||||
|
// Optionally, log or update UI state to reflect that the game was added
|
||||||
|
} catch (e: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAllCategories() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val categories = withContext(Dispatchers.IO) {
|
||||||
|
repository.getAllCategories()
|
||||||
|
}
|
||||||
|
categoryUiState = CategoryListUIState(categories)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user