kotlin-multiplatformsqldelight

Using SqlDelight with Flow and also mapping Entities to a wrapper object


I am using SqlDelight and Kotlin Multiplatform and am wondering if there is a way to map the returned record entities to a helper class before returning the Flow.

Here is normal usage:

val players: Flow<List<HockeyPlayer>> = 
  playerQueries.selectAll()
    .asFlow()
    .mapToList()

I want to do something like this:

val players: Flow<List<HockeyPlayer>> = 
  playerQueries.selectAll()
    .map { it.toOtherClass() }
    .asFlow()
    .mapToList()

Is there a way to do this? I'm a Kotlin n00b so I feel like I'm missing something obvious


Solution

  • selectAll() returns a Query, so any mapping of result entities needs to happen after the asFlow() extension, and the query needs to be executed, i.e. executeAsList() for fetching the updated result as list.

    An example could look like this:

    val players: Flow<List<HockeyPlayer>> = 
      playerQueries.selectAll()
        .map { it.toOtherClass() }
        .asFlow()
        .map { query ->
          query.executeAsList().map { it.toOtherClass() } 
        }