I want to display a list of items using LazyColumn. I wrote the needed code but when I ran the app I observed that the UI is very laggy. I put some Logs to find out where the problem may be and I discovered that the LazyColumn inifinitely recomposes the items. I replaced the LazyColumn with a Column with scrollable modifier and the problem was gone in this case. But I don't know why LazyColumn behaves like it did.
The list is this:
var rides = mutableStateListOf<Ride>(Ride(...), Ride(...))
A list item is like this:
@Stable
@Entity(tableName = "ride_table")
data class Ride(
var img: Bitmap? = null,
var path: List<List<LatLng>>? = null,
var cities: List<String>? = null,
var timeStarted: Long = 0L,
var timeEnded: Long = 0L,
var avgSpeedInKmh: Float = 0f,
var maxSpeedInKmh: Float = 0f,
var distanceInMeters: Float = 0f,
var totalTimeInSeconds: Long = 0L,
@PrimaryKey(autoGenerate = true)
var id: Long = 0L
) {
override fun equals(other: Any?): Boolean {
if(other == null)
return false
if(other is Ride) {
return id == other.id
} else {
return false
}
}
}
The list composable:
@Composable
fun Rides(rides: List<Ride>) {
Log.d("RECOMPOSE", "1")
LazyColumn {
items(rides) { ride ->
Log.d("RECOMPOSE", "2")
RideDetails(ride)
}
}
/*Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
rides.forEach { ride ->
Log.d("RECOMPOSE", "2")
RideDetails(ride)
}
}*/
}
RideDetails:
@Composable
fun RideDetails(ride: Ride) {
Log.d("RECOMPOSE", "3`")
Text(text = "ride ${ride}")
}
Log Recompose 2 gets called non stop in the case of LazyColumn. If I switch to Column this doesn't happen and the number of Log calls is the expected one. What am I doing wrong using LazyColumn?
UPDATE (The below Column gets called inside the setContent that lies in onCreateView)
Column {
val cities = rideViewModel.cities
val filterCities = rideViewModel.filterCities
val rides = rideViewModel.rides
TopBar {
...
}
Chips(cities, filterCities)
Log.d("RECOMPOSE", "RECOMPOSE INSIDE SCREEN")
Rides(rides)
}