https://kotlinlang.org logo
Title
a

Ayla

05/05/2023, 6:04 AM
Hi, I'm developing a note app, in the homepage I want to show the notes token today, so I use the SQLDelight flow extension. The problem is when the date changes, I need cancel the previous flow and create a new flow.
val tempJob:Job? = null
fun getNotesToday(today:LocalDate){
viewModelScope.launch{
tempJob?.cancel()
tempJob=launch{
database.noteQuery
.getNotesBetween(today.start,today.end)
.asFlow()
.collectLatest{...}
}
}
It seems a bit troublesome to do the same for every situation like this, is there a better way?
g

glureau

05/05/2023, 6:58 AM
Have you tried to use SQL to compute the dates? Not sure if sqldelight listeners will work properly then, it's a genuine question.
h

hfhbd

05/05/2023, 7:54 AM
I don’t think the database will trigger something if the date will change out of the box. I guess, you will need a trigger. But are you sure you need to keep the tempJob at all? The flow is cancelable.
f

florent

05/05/2023, 8:11 AM
I would put today's date in a shared flow and do a flatmaplatest with the sqldelight flow
a

Ayla

05/05/2023, 10:44 AM
Thank you all. I store the datetime as Long type, so the sql date() function may be not suitable. Sure a trigger is needed as said , and using shared flow with platform events is a good way.
Besides, about the tempJob, I am kind of confused, if don't keep it , how to cancel the previous flow when the method is called again?
f

florent

05/05/2023, 11:25 AM
You would use the viewModelScope and let it manage the lifecycle for you
s

Stylianos Gakis

05/06/2023, 8:22 PM
flowThatReturnsCurrentDay().collectLatest { date ->
  yourDbFlow.collect { ... }
}
This by itself should cancel the old collection, and start a new one with the new date. Just need to create a flow which returns this date somehow.
a

Ayla

05/07/2023, 10:27 AM
Thanks all, I'll have a try☺️