Spot the bug
Tapping Add doesn't update the list on screen. Which line is the bug?
class CartViewModel : ViewModel() {private val items = mutableListOf<String>()val state = MutableStateFlow<List<String>>(items)fun add(item: String) {items.add(item)state.value = items}}
Hint 1 of 1
Is the new value a different list from the old one?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 7
state.value = items
The same list object is assigned back, so the new value equals the old one and StateFlow emits nothing. Use state.update { it + item } with an immutable list.