If I want to make a server request, but also, at t...
# coroutines
s
If I want to make a server request, but also, at the same time subscribe to further updates of that data from a StateFlow (driven separately by something i.e. a push message telling the app the data is fresh), what would the best way to do that? Something to keep in mind is I need to pass exceptions from the server request though as well. I haven’t found an elegant way to do this without it getting messy.
i.e.
Copy code
private val headlinesStateFlow = MutableStateFlow<List<Headline>?>(null)

suspend fun headlines(): Flow<List<Headline>> = flow {
    coroutineScope {
        async {
            headlinesStateFlow.emit(videoService.getHeadlines())
        }

        emitAll(headlinesStateFlow.filterNotNull())
    }
}
z
Are you saying that code snippet looks messy to you?
Also that should be
launch
not
async
s
oops, yeah, I was playing around with it
I guess that does exactly what I want it too.
actually it doesn’t, but I suppose this does:
Copy code
suspend fun headlines(): Flow<List<Headline>> = flow {
    coroutineScope {
        headlinesStateFlow.emit(videoService.getHeadlines())
        emitAll(headlinesStateFlow.filterNotNull())
    }
}
I’m not entirely certain what would have happened to the server errors in the original
launch
z
they’d have been propagated through your flow due to structured concurrency
s
I thought launch would have transferred it to the ExceptionHandler.
it only would propagate I thought if I did
async / await
z
if you use
async
without
await
it will actually not propagate at all, just drop.
a
You can use
flow
builder and
stateIn
like the example shown here.
s
Hey! this looks promising. The example code in the documentation doesn’t make it obvious how to use it though. A few pieces are missing i think.