0

I have following composable

@Composable
fun ManageCredential(
    manageCredentialViewModel: ManageCredentialViewModel
) {
val expandedList by manageCredentialViewModel.expandedList.collectAsState()
val text = "Hello"

    Scaffold(
        modifier = Modifier.padding(top = 100.dp),
        content = { padding ->
        Image(
            painter = if (expandedList.contains(text)) painterResource(id = R.drawable.drop_down_expand) else painterResource(
                id = R.drawable.drop_down_collapse
            ),
            contentDescription = text, modifier = Modifier.padding(padding).clickable {
                if (expandedList.contains(text)) {
                    manageCredentialViewModel.removeFromList(text)
                } else {
                    manageCredentialViewModel.addToList(text)
                }
            }
        )
    })
}

The view model is as follows

@HiltViewModel
class ManageCredentialViewModel @Inject constructor(
) : ViewModel() {

    private val _expandedList = MutableStateFlow<MutableList<String>>(mutableListOf())
    val expandedList = _expandedList.asStateFlow()
 fun addToList(value: String) {
        _expandedList.value.add(value)
    }

    fun removeFromList(value: String) {
        _expandedList.value.remove(value)
    }
}

I just want to toggle the image if a particular text is added to the list but it never happens

BraveEvidence
  • 53
  • 11
  • 45
  • 119

1 Answers1

1

For recomposition to be triggered you need to change value of State. What you currently do is adding or removing items from existing list.

You can create SnapshotStateList with mutableStateListOf. Any changes in this list by removing, adding or updating an existing item with a new item, easily can be done with data class copy function, you can trigger recomposition and good thing about it is it only triggers recomposition for the Composable that reads that item such as LazyColumn item.

You can refer this answer also

Jetpack Compose lazy column all items recomposes when a single item update

Thracian
  • 43,021
  • 16
  • 133
  • 222
  • I tried what you said. Here is the gist https://gist.github.com/BraveEvidence/dd5e20838faf56c6f21ad4b7c3d3e2cb. Can you please check and tell what am I missing? – BraveEvidence Feb 18 '23 at 09:18
  • First of all you don't MutableStateFlow. SnapshotStateList takes care of recomposition and. Instead of iterating with any you can create a data model with expanded flag and update existing element with index by getting that element and changing it's expand flag. Let me post another example with selection. You can change isSelected to isExpanded and change any property based on your flag. https://stackoverflow.com/questions/74673210/how-to-select-multiple-items-in-lazycolumn-in-jetpackcompose/74673860#74673860 – Thracian Feb 18 '23 at 09:23