open class RecipeStepBottomViewModel : GoBongViewModel() {
private val _thumbnailByteArray = MutableStateFlow(byteArrayOf())
val thumbnailByteArray: StateFlow<ByteArray> get() = _thumbnailByteArray
private val _minute = MutableStateFlow("0")
val minute: StateFlow<String> get() = _minute
private val _second = MutableStateFlow("0")
val second: StateFlow<String> get() = _second
val descriptionInputText = MutableStateFlow("")
private val _tools = MutableStateFlow(
listOf(
Tool("전자레인지", false, true),
Tool("에어프라이어", false, true),
Tool("오븐", false, true),
Tool("가스레인지", false, true),
Tool("믹서", false, true),
Tool("커피포트", false, true),
Tool("프라이팬", false, true)
)
)
val tools: StateFlow<List<Tool>> get() = _tools
private val _isSavedSuccess = MutableStateFlow(false)
val isSavedSuccess: StateFlow<Boolean> get() = _isSavedSuccess
fun setSuccess(isSuccess: Boolean) {
_isSavedSuccess.value = isSuccess
}
fun setThumbnailByteArray(byteArray: ByteArray) {
_thumbnailByteArray.value = byteArray
}
fun setDescriptionText(text: String) {
descriptionInputText.value = text
}
}
ui state를 가지고 있는 변수와 그 변수를 set,get하는 함수들을 가지고 있다.
class RecipeStepAddBottomViewModel : RecipeStepBottomViewModel() {
fun saveNewRecipeStep() {
viewModelScope.launch {
try {
isSaveValidate()
requestNewRecipe()
} catch (e: Exception) {
setToastMessage(e.message ?: "")
}
}
}
private suspend fun requestNewRecipe() {
setSuccess(true)
}
fun getNewRecipeStep(): RecipeStepAdded {
return RecipeStepAdded(
"${minute.value}분 ${second.value}초",
tools.value.filter { it.isChecked }.map { it.toolName },
thumbnailByteArray.value,
descriptionInputText.value
)
}
}
새로운 recipe 단계를 추가하는 메서드를 가지고 있다.
class RecipeStepEditBottomViewModel : RecipeStepBottomViewModel() {
private val _isDeleted = MutableStateFlow(false)
val isDeleted: StateFlow<Boolean> get() = _isDeleted
private var editId = 0L
fun getStepId() = editId
fun setOldRecipe(recipe: RecipeStepAdded) {
setThumbnailByteArray(recipe.photoUrl)
checkTools(recipe.tools)
val times = recipe.time.split(" ")
addMinute(times[0].removeSuffix("분").toInt())
addSecond(times[1].removeSuffix("초").toInt())
setDescriptionText(recipe.description)
editId = recipe.id
}
fun updateRecipeStep() {
try {
isSaveValidate()
requestUpdatedRecipeStep()
} catch (e: Exception) {
setSuccess(false)
setSnackBarMessage(e.message ?: "")
}
}
private fun requestUpdatedRecipeStep() {
setSuccess(true)
}
edit의 경우 기존 데이터가 초반에 미리 세팅이 되어 있어야 함으로 setOldRecipe같은 메서드를 가진다.
또한, update나 delete가 되었는지, edit하고 있는 게시물의 Id 등등을 가지고 있다.