androidandroid-room

How to make data retrieval from Room Fast


I am retrieving data from the room database using this code. it takes around 2 seconds to fetch and display data on the screen. The table has 10k rows.

Table

@Entity("RoomTrains")
data class TrnTable(
@PrimaryKey
val num:Int=0,
val name:String="",
val type:Int=0,
val srCode:String="",
val srcName:String="",
val destCode:String="",
val destName:String="",
val runDays:Int=0,
val classes:String="",
val totalDist:Float=0.0f,
val jourTime:Int=0,
val depArr:String="",
val updatedOn:Int=0)

Dao

@Query("SELECT * FROM RoomTrains")
abstract  fun getTrains(): Flow<List<TrnTable>>

Repository

fun getAllTrains(): Flow<List<TrnTable>> {
    return trainDao.getTrains()
}

View model

 val allTrainsFromTrnTableSF: StateFlow<List<TrnTable>> = chukRepository.getAllTrains()
    .stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(),
        initialValue = emptyList(),
    )

UI Page

    val trainList by viewModel.allTrainsFromTrnTableSF.collectAsState(initial = emptyList())
     LazyColumn(modifier = Modifier.background(Color.LightGray)) {
            items(trainList) { train ->
            //data displayed using Card()
              }
        }

Solution

  • I am retrieving data from the room database using this code. it takes around 2 seconds to fetch and display data on the screen. The table has 10k rows.

    In this case you are getting all data from this table("RoomTrains"), if the table increases, so the time and memory consume probably will increase. Therefore, I'd suggest you work with pagination. In this way you can get the data as needed, for example, as the user scroll. Room library can delivery for you a PagingSource from your query, as exemplified below (example from Android documentation):

    @Query("SELECT * FROM users WHERE label LIKE :query")
    fun pagingSource(query: String): PagingSource<Int, User>
    

    As you are using Compose, it has this function collectAsLazyPagingItems, so you can collect the items. This Android documentation has a sample code.

    Adapted from Paging library fits into your app architecture][3]