recipe-kt/app/src/main/java/xyz/pixelatedw/recipe/data/RecipesView.kt

58 lines
1.6 KiB
Kotlin

package xyz.pixelatedw.recipe.data
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class RecipesView : ViewModel() {
private val _activeRecipe = MutableStateFlow<RecipeWithTags?>( null )
val activeRecipe = _activeRecipe.asStateFlow()
private val _recipes = MutableStateFlow<List<RecipeWithTags>>( arrayListOf() )
val recipes = _recipes.asStateFlow()
private val _tagFilters = MutableStateFlow<List<TagFilter>>( arrayListOf() )
val tagFilters = _tagFilters.asStateFlow()
private val _search = MutableStateFlow<String?>(null)
val search = _search.asStateFlow()
private val _keepScreenOn = MutableStateFlow<Boolean>(false)
val keepScreenOn = _keepScreenOn.asStateFlow()
fun setTagFilterState(tag: String, state: Boolean) {
_tagFilters.value = _tagFilters.value.toMutableList().apply { replaceAll { it -> if (tag == it.tag) it.checked = state; it } }.toList()
}
fun setKeepScreenOn(flag: Boolean) {
_keepScreenOn.update { flag }
}
fun setRecipes(recipes: List<RecipeWithTags>) {
_recipes.update { recipes }
val filters = arrayListOf<TagFilter>()
_recipes.value.stream()
.filter { it.tags.isNotEmpty() }
.forEach {
it.tags.forEach {tag -> filters.add(TagFilter(tag.name))}
}
_tagFilters.update { filters.distinct() }
}
fun removeRecipe(recipe: RecipeWithTags) {
_recipes.value = _recipes.value.toMutableList().apply { remove(recipe) }.toList()
}
fun setSearch(search: String) {
_search.update { search }
}
fun setActive(recipe: RecipeWithTags) {
_activeRecipe.update { recipe }
}
}