'The LazyColumn is always reload twice, it has duplicate content twice

This is my code:

@Composable
fun GetPathList(context: Activity, path: String) {
    val resultJson = remember { mutableStateListOf<RequestData.PathData>() }
    var loadingPicController by remember { mutableStateOf(true) }
    if (loadingPicController) {
        Text("loading")
    }
    thread {
        resultJson.addAll(RequestData().getPath(path))
        loadingPicController = false // Loading End
    }
    LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        items(resultJson) { item ->
            Surface(modifier = Modifier.clickable {
                val intent = Intent(context, PathDetailsActivity::class.java)
                intent.putExtra("folderName", item.name)
                intent.putExtra("path", "$path/${item.name}")
                context.startActivity(intent)
            }) {
                Row(
                    modifier = Modifier
                        .padding(start = 24.dp, top = 8.dp, bottom = 8.dp)
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Icon(painter = Icons.Document, contentDescription = "Files", modifier = Modifier.size(28.dp))
                    Column(modifier = Modifier.padding(start = 16.dp)) {
                        Text(item.name, fontWeight = FontWeight.Medium, fontSize = 14.sp)
                        Text(item.type, fontWeight = FontWeight.Light, fontSize = 12.sp)
                    }
                }
            }
        }
    }
}

The right result is here
enter image description here
However, With the code , After the loading finshing, the list was reloaded twice. it should only load once.
But now after the loading animation is over it is loaded twice and the content is repeated twice enter image description here
enter image description here



Solution 1:[1]

This is happening because every time your composable function is executed, a new thread is started and it's adding all the items again. Basically the current flow is:

  1. GetPathList is executed. The loadingPicController is true and a new thread is executed.

  2. When the thread finishes, the loadingPicController flag is set to false, causing a recomposition (GetPathList is called again).

  3. GetPathList is called again. The thread is triggered again, adding the items again. Since loadingPicController is false already, the recomposition didn't happen.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nglauber