4

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

mike so
  • 337
  • 1
  • 3
  • 7
  • Check out [this answer](https://stackoverflow.com/a/69629575/3585796) of the ways to correctly get initial data. – Phil Dukhov Apr 17 '22 at 04:51

2 Answers2

2

Items come with a key parameter that you can use to prevent any duplicates and also to ensure that if there is an update the right item is updated. in any case if this fails you can use list.distinct() to help clear out any duplicates

BrianDev
  • 476
  • 5
  • 10
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.

nglauber
  • 18,674
  • 6
  • 70
  • 75