Im using a `Flow<T>` which queries data from...
# coroutines
z
Im using a
Flow<T>
which queries data from an SQL database, initially emitting the current version of the data, and then emitting again anytime it changes. Is it possible to collect the flow in a way such that the initial query isnt re-ran everytime I restart collecting it? Consider a component that can be started/stopped, if the initial query has finished it wouldnt make sense to re-run it the next time the component is started, Id much prefer to just receive any further changes to it. The natural approach seems to be collecting the flow in start, cancelling the resulting job in stop - as expected that restarts the collection everytime though.
g
You can use shared flow with buffer=1 for this, though it will not be the initial query, but the last result If you need only first one (though I’m not sure what is use case for this) you can just cache this value and create flow with cached value
z
Do you mean
flow.buffer(1).shareIn(scope, Lazily)
? If I understand it correctly, the query will remain active and its last value will continiously be put in the shared-flow buffer, which the consumer component will receive when it resumes in collecting it? I guess that would work, but what Im really after is also stopping the queries from running if there are no subscribers at the time.
WhileSubscribed
sounds like it would do that, but it resets after a timeout and is similar to
Lazily
with an infinite timeout (I think).
g
WhileSubscribed
sounds like it would do that
Correct
but it resets after a timeout
What do you mean? you can make it with or without timeout, up to you
z
Perhaps easier described with another exampe. If I were to use a flow that just emits numbers in sequence with `WhileSubscribed`; - stopTimeoutMillis=Long.MAX_VALUE => The counter would just continue forever, similar to
Lazily
- stopTimeoutMillis=0 (default) => The counter would continue as long as the client is subscribed, but restart at 0 after every stoppage What I actually want is for the counter to keep counting as long as someone is subscribed, pausing at the current number when the subscriber unsubscribes - and then continue counting from that number whenever that someone re-subscribes.
g
There is no such feature on Flow ready to use, but you can easily do this if just keep counter state on level of Flow instance, in global memory or in some persistent storage. So essentially you need stopTimeoutMillis=0 with state
z
Thanks for getting back to me @gildor! That makes sense, Ill see whether or not I can apply it to my use case 👍🏽