https://kotlinlang.org logo
Title
s

Stylianos Gakis

04/18/2023, 10:01 AM
I may be misunderstanding you here, but if you are reading it as a flow, and are maybe doing a
mapLatest
on it which in that lambda you’re doing all this processing, if the DB emits a new value into that flow, your previous calculation should be cancelled and you will get the fresh data automatically.
a

adte

04/18/2023, 4:02 PM
@Stylianos Gakis If I have a list of ids and I'm making queries to the db in a loop like this: fun getData(ids: List<Long>) { ids.forEach { id -> queries.getFlowForId(id) } // return a Flow? } How can I combine that into a single flow?
It sounds like how I could do this is make a single query to the table I'm interested in, so that I get the enclosing flow, and then put all my logic inside a
map
function and not deal with any flow inside there
s

Stylianos Gakis

04/18/2023, 8:18 PM
Hmm can you try taking the IDs to make a list of your possible Flows, and then using a
combine
on those so that you get them all together in one flow, and then do whatever you want with them. Gonna paste some code that I used just to make sure that the types all play well together.
object queries {
  fun getFlowForId(id: Long): Flow<Int> = flowOf()
}

fun getData(ids: List<Long>): Flow<List<Int>> {
  val allFlows: List<Flow<Int>> = ids.map {
    queries.getFlowForId(it)
  }
  return combine(allFlows) { flows: Array<Int> ->
    flows.toList()
  }.mapLatest {
    //do stuff here
    it
  }
}
Does this look like what you’re looking for?
a

apsaliya

04/19/2023, 5:42 AM
since SQLDelight queries are executed only when one of the
execute
is called, you can do something like this. This will execute your mapper every time user table is updated.
notificationQuery: SELECT * FROM USER
// this query will only be used for observing changes in User table
...
...
notificationQuery.asFlow()
.map {
 // val user = databse.queries.fetchById().executeAsOne()
 // map to the type you want
}