Trong Compose đối với LazyColumn dựa vào gì để so sánh dữ liệu mới và cũ đổ vào list để…
- User
Trong Compose đối với LazyColumn dựa vào gì để so sánh dữ liệu mới và cũ đổ vào list để hiển thị, tránh tạo lại những item đã có mà chỉ tạo những item cần thiết
- Assistant
Trong LazyColumn, Compose sử dụng key để identify và so sánh các items, từ đó quyết định item nào cần recompose, item nào có thể tái sử dụng.
Cơ chế Key-based Identification
LazyColumn { items( items = userList, key = { user -> user.id } // Key để identify mỗi item ) { user -> UserItem(user = user) } }Quá trình hoạt động:
- Compose tạo một mapping giữa key và composable content
- Khi dữ liệu thay đổi, Compose so sánh các key cũ và mới
- Items có key giống nhau sẽ được reuse, chỉ recompose nếu content thay đổi
- Items có key mới sẽ được tạo mới
- Items không còn key tương ứng sẽ bị dispose
Stable vs Unstable Objects
Compose cũng dựa vào tính stability của objects:
// Stable - Compose có thể skip recomposition @Stable data class User(val id: String, val name: String) // Unstable - luôn trigger recomposition class MutableUser(var name: String)Smart Recomposition
@Composable fun UserItem(user: User) { // Chỉ recompose khi user object thay đổi Column { Text(user.name) Text(user.email) } }Compose sử dụng structural equality và referential equality để detect changes:
- Nếu object reference giống nhau → skip recomposition
- Nếu object khác nhau nhưng content giống nhau (với @Stable) → có thể skip
- Nếu object unstable → luôn recompose
Best Practices
Sử dụng key phù hợp:
// Tốt - sử dụng unique, stable key key = { item -> item.id } // Tránh - sử dụng index có thể gây confusion khi data thay đổi key = { index -> index }Optimize data classes:
@Stable data class ListItem( val id: String, val title: String, val isSelected: Boolean )Nhờ cơ chế này, LazyColumn có thể hiệu quả tránh việc recreate các items không cần thiết, chỉ update những gì thực sự thay đổi, giúp performance tốt hơn đáng kể so với việc recreate toàn bộ list.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.