https://kotlinlang.org logo
#android
Title
# android
s

Shawn Witte

06/09/2020, 1:40 AM
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

Ryan

06/09/2020, 4:02 AM
if your using room, you can use the Observable or LiveData
so when you insert data it will broadcast
s

Shawn Witte

06/09/2020, 4:07 AM
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

Kit

06/09/2020, 11:01 AM
stateFlow
?
p

Paul Woitaschek

06/09/2020, 4:12 PM
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

Shawn Witte

06/09/2020, 4:28 PM
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

Paul Woitaschek

06/09/2020, 4:37 PM
Why do you need a service and what does it?
s

Shawn Witte

06/09/2020, 4:44 PM
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.