Hi guys, `I keep getting java.lang.IllegalArgument...
# android
r
Hi guys,
I keep getting java.lang.IllegalArgumentException: Key was already used. If you are using LazyColumn/Row please make sure you provide a unique key for each item.
I am sure all the keys are unique and I even logged them to be sure. Also this happens when items are rapidly added to lazy column. Here is my sample code:
Copy code
@Composable
fun UiComponent() {
    LazyColumn(
                verticalArrangement = Arrangement.spacedBy(12.dp),
                state = scrollState,
                reverseLayout = true
            ) {
                items(
                    items = viewmodel.messages,
                    key = { item -> item.hashcode() },
                    itemContent = { item: Entity ->
                        if (item.isDeleted) {
                            //show deleted ui
                        } else {
                            //show messages
                        }
                    })
            }
        }
}

VM {

    init { 
       observeDataFromDB()
    }

    private val _messages: MutableList<Entity> = mutableStateListOf()
    val messages: List<Entity> = _messages


    fun observeDataFromDB() {
        viewModelScope.launch {
            repo.getData().collect {
                _messages.apply {
                    addNewItem(it)
                }
            }
        }
    }

}


//extensions
fun MutableList<Entity>.addNewItem(entity: Entity) {
    if (this.size >= MAX_SIZE) {
        removeLast()
    }
    Log("existing ${this.toList().map { "${it.hashCode()}" }}")
    Log("adding new ${entity.hashCode()}")
    this.add(0, entity)
}

//id is primary key
data class Entity(val id: String, val isDeleted: Boolean, val message: String)
Any help would be great! Have been stuck with this for sometime now and not sure how to proceed 😭 Have tried using
id
as the key and I still get the same error.
a
#compose
r
Sorry will post it there as well 👍
Please follow the thread in #compose https://kotlinlang.slack.com/archives/CJLTWPH7S/p1636121092497900 Sorry for the inconvenience.