From f246d2efbbc0acb09a41211a3df514827fe55858 Mon Sep 17 00:00:00 2001 From: Florian Date: Wed, 15 Jan 2025 10:48:36 +0100 Subject: [PATCH] .. --- .../ledger/ui/category/CategoryViewModel.kt | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/Ledger/app/src/main/java/at/xaxa/ledger/ui/category/CategoryViewModel.kt b/Ledger/app/src/main/java/at/xaxa/ledger/ui/category/CategoryViewModel.kt index e1eff0e..2aee3a9 100644 --- a/Ledger/app/src/main/java/at/xaxa/ledger/ui/category/CategoryViewModel.kt +++ b/Ledger/app/src/main/java/at/xaxa/ledger/ui/category/CategoryViewModel.kt @@ -1,2 +1,61 @@ 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> = 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) + + } + + } +}