Hey everyone, I'm looking for some advice on the b...
# android
s
Hey everyone, I'm looking for some advice on the best way to do something with coroutines. I've got a service that I need to produce data at a certain interval. Only the most recent data is relevant (e.g. elapsed time, etc.). I have a view that binds to this service that I would like to update either whenever the data is updated or possibly at a slightly longer interval. I'm wondering how people would implement this via coroutines. I'm thinking a service-scoped coroutine that looks like
Copy code
while(true) {
    delay(interval)
    updateDataObject()
}
Then I'm thinking of launching a coroutine in my ViewModel that looks the same except it's pulling the data out of the binding after each interval instead of generating it. Is there a better way with Channels or Flow? Or is this a reasonable approach?
r
if your using room, you can use the Observable or LiveData
so when you insert data it will broadcast
s
We're also using MvRx to implement an MVI structure, so we're not using LiveData. Also MvRx is working on getting rid of RxJava as a dependency, and I'd like to move away from Rx as well.
k
stateFlow
?
p
I'd put a MutableStateFlow in some sort of application Singleton and subscribe to the flow from the viewModel and let the service push updates
s
Yeah I'm looking at StateFlow now. It looks like what I want. Can you clarify the part about using an application singleton, @Paul Woitaschek? I was going to just send a StateFlow through the binding and let the MutableStateFlow live in the (Foreground)Service.
p
Why do you need a service and what does it?
s
The short version is that the service tracks location data for the user. It needs to survive until intentionally dismissed, and the user should be aware when it is running. Hence, ForegroundService.