-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathDessertViewModel.kt
More file actions
56 lines (49 loc) · 2.12 KB
/
DessertViewModel.kt
File metadata and controls
56 lines (49 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.dessertclicker.ui
import androidx.lifecycle.ViewModel
import com.example.dessertclicker.data.DessertUiState
import com.example.dessertclicker.data.Datasource.dessertList
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class DessertViewModel : ViewModel() {
private val _dessertUiState = MutableStateFlow(DessertUiState())
val dessertUiState: StateFlow<DessertUiState> = _dessertUiState.asStateFlow()
fun onDessertClicked(){
_dessertUiState.update { cupCakeUiState ->
val dessertsSold: Int = if (cupCakeUiState.currentDessertIndex >= 13){
cupCakeUiState.dessertsSold
}else{
cupCakeUiState.dessertsSold + 1
}
val nextDessertIndex = determineDessertIndex(dessertsSold)
if(cupCakeUiState.currentDessertIndex >= 13){
cupCakeUiState.copy(
currentDessertIndex = nextDessertIndex,
dessertsSold = dessertsSold,
revenue = cupCakeUiState.revenue,
currentDessertPrice = dessertList[nextDessertIndex].price,
currentDessertImageId = dessertList[nextDessertIndex].imageId
)
}else{
cupCakeUiState.copy(
currentDessertIndex = nextDessertIndex,
dessertsSold = dessertsSold,
revenue = cupCakeUiState.revenue + cupCakeUiState.currentDessertPrice,
currentDessertPrice = dessertList[nextDessertIndex].price,
currentDessertImageId = dessertList[nextDessertIndex].imageId
)
}
}
}
private fun determineDessertIndex(dessertsSold: Int): Int {
var dessertIndex = 0
for (index in dessertList.indices) {
if (dessertsSold >= dessertList[index].startProductionAmount) {
dessertIndex = index
}
}
return if (dessertIndex <= 12) dessertIndex
else 13
}
}