Skip to content

Commit

Permalink
feat: hide suggest another button if single item
Browse files Browse the repository at this point in the history
  • Loading branch information
aslansari committed May 17, 2024
1 parent 094b7d9 commit ee49681
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
Expand Down Expand Up @@ -97,10 +99,16 @@ internal fun CocktailScreen(
Spacer(Modifier.size(12.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedButton(onClick = onBackClick) {
Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
Spacer(Modifier.size(2.dp))
Text("Change Flavor")
}
OutlinedButton(onClick = onSuggestAnotherClick) {
Text("Suggest Another")
if (uiState.showSuggestAnother) {
OutlinedButton(onClick = onSuggestAnotherClick) {
Icon(imageVector = Icons.Default.Refresh, contentDescription = "Refresh")
Spacer(Modifier.size(2.dp))
Text("Suggest Another")
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,21 @@ class CocktailViewModel : BaseViewModel<CocktailUIState>() {

fun updateArgs(args: CocktailArgs) {
this.args = args
setState { copy(category = args.category) }
setState { copy(category = args.category, selectedIndex = -1) }
viewModelScope.launch(Dispatchers.Default) {
selectCocktailByFlavor(args.category)
}
}

fun selectCocktailByFlavor(flavor: String) {
private fun selectCocktailByFlavor(flavor: String) {
val cocktails = cocktailsByFlavor[flavor]
if (!cocktails.isNullOrEmpty()) {
val cocktail = cocktails.random()

setState { copy(showSuggestAnother = cocktails.size > 1) }

val randomIndex = randomExcept(currentState.selectedIndex, cocktails.lastIndex)
setState { copy(selectedIndex = randomIndex) }
val cocktail = cocktails[randomIndex]
setState {
copy(
title = cocktail.title,
Expand All @@ -50,6 +55,11 @@ class CocktailViewModel : BaseViewModel<CocktailUIState>() {
}
}

private fun randomExcept(except: Int, size: Int): Int {
val random = (0 .. size).filter { it != except }.random()
return random
}

fun suggestAnother() {
viewModelScope.launch(Dispatchers.Default) {
args?.let {
Expand Down Expand Up @@ -100,4 +110,6 @@ data class CocktailUIState(
val category: String = "",
val title: String = "",
val cocktailImageUrl: String = "",
val selectedIndex: Int = -1,
val showSuggestAnother: Boolean = false,
) : UIState

0 comments on commit ee49681

Please sign in to comment.