Skip to content

Instantly share code, notes, and snippets.

@bsscco
Last active June 22, 2022 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsscco/7bcb8cd7289fa933dc8689db39ef6fa0 to your computer and use it in GitHub Desktop.
Save bsscco/7bcb8cd7289fa933dc8689db39ef6fa0 to your computer and use it in GitHub Desktop.
Compose에서 key 컴포저블 사용하기
var items by remember {
mutableStateOf((0 until 1000).toList())
}
val scope = rememberCoroutineScope()
ItemList(
items = items,
onItemClick = {
// scope 안에서 데이터를 변경하면 key가 재역할을 하지 못한다. ViewModel에서 데이터를 변경해도 마찬가지일 것. rememberUpdatedState()의 개념이 힌트일지도 모르겠다.
// LazyColumn에선 key가 재역할을 못하더라도 화면에 보여지는 항목들만 Recomposition 대상으로 삼기 때문에 성능문제가 크진 않다.
// scope.launch {
val newItems = items.takeLast(items.size - 1)
items = newItems
// }
},
)
@Composable
private fun ItemList(items: List<Int>, onItemClick: (Int) -> Unit) {
LazyColumn(Modifier.fillMaxSize()) {
items(
items = items,
key = { item -> item }
) { item ->
// 이 위치에선 아래와 같이 @Composable 함수를 호출하지 않고 Box { ... } 처럼 직접 풀어쓰면 key가 재역할을 하지 못한다. 원인 모름.
// 이 위치에선 아래와 같이 @Composable 함수를 호출하는 것 외에 실행코드 한 줄이라도 있으면 key가 재역할을 하지 못한다. 예) Log.e("BSSCCO", "$item"). 원인 모름.
Item(item, onClick = { onItemClick(item) })
}
}
}
@Composable
private fun Item(item: Int, onClick: () -> Unit) {
Box(
modifier = Modifier
.clickable(onClick = onClick)
.fillMaxWidth()
.height(50.dp),
contentAlignment = Alignment.Center,
) {
Log.e("BSSCCO", "$item")
Text(item.toString())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment