Hi I have an app with Jetpack Compose that has a list and user can add or delete items in that list. That list also recording to the FireBaseFireStore. Updating added items synchronously is successful but when i try to delete an item from list, LazyColumn's behaviour is being weird. İt deletes all items sometimes or delete selected item and under of it. I guess that's because i'm using list.clear() method in my retriever function but if I don't use clear() method then it duplicates items when i try to add another item. So how can i solve that problem ? If i use arrayList instead of MutableStateList then deleting operation being succesful but then lazyColumn does not update itself when adding the new item. I'm in a paradox pls help me.
Here is my code snippets :
DataRetriever Function:
override suspend fun getAnalysisListFromFirebase(
analyzeList: MutableList<AnalyzeModel>,
currentPairId: String
) {
pairCollection
.document(currentPairId)
.collection("Analysis").orderBy("date", Query.Direction.DESCENDING)
.addSnapshotListener { value, error ->
try {
if (value != null && !value.isEmpty) {
val documents = value.documents
analyzeList.clear()
documents.forEach {
val analyze = it.toObject(AnalyzeModel::class.java)
if (analyze != null) {
analyzeList.add(analyze)
}
}
} else if (error != null) {
Toast.makeText(Application(), error.localizedMessage, Toast.LENGTH_LONG)
.show()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Delete From Firebase Function :
override suspend fun deleteFromFirebase(analyzeId: String,pairId: String, context: Context) {
try {
pairCollection.document(pairId).collection("Analysis").document(analyzeId).delete().await()
}catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(context, e.localizedMessage, Toast.LENGTH_LONG).show()
}
}
}
Lazy Column Composable :
Surface(modifier = Modifier
.fillMaxSize()
.padding(it)
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
HeaderText(header = pairName, modifier = Modifier)
LazyColumn() {
items(analyzeList) { analyze ->
val swipeToDeleteState = rememberDismissState(
confirmStateChange = {
if (it == DismissValue.DismissedToStart) {
scope.launch {
viewModel.deleteFromFirebase(analyze.id,currencyId)
analyzeList.remove(analyze)
}
}
true
}
)
SwipeToDismiss(
state = swipeToDeleteState,
background = {
val color = when (swipeToDeleteState.dismissDirection) {
DismissDirection.EndToStart -> Color.Red
DismissDirection.StartToEnd -> Color.Transparent
null -> Color.Transparent
}
Box(
modifier = Modifier
.fillParentMaxSize()
.background(color = color)
.padding(8.dp)
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Delete",
tint = Color.White,
modifier = Modifier.align(Alignment.CenterEnd)
)
}
},
dismissContent = {
AnalyzeRow(analyze = analyze)
},
directions=setOf(DismissDirection.EndToStart)
)
}
}
}
}
Thanks in advance.