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

spierce7

02/28/2021, 1:09 AM
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

Zach Klippenstein (he/him) [MOD]

02/28/2021, 1:36 AM
Are you saying that code snippet looks messy to you?
Also that should be
launch
not
async
s

spierce7

02/28/2021, 2:03 AM
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

Zach Klippenstein (he/him) [MOD]

02/28/2021, 2:30 AM
they’d have been propagated through your flow due to structured concurrency
s

spierce7

02/28/2021, 2:46 AM
I thought launch would have transferred it to the ExceptionHandler.
it only would propagate I thought if I did
async / await
z

Zach Klippenstein (he/him) [MOD]

02/28/2021, 3:06 AM
if you use
async
without
await
it will actually not propagate at all, just drop.
a

Albert Chang

02/28/2021, 3:49 AM
You can use
flow
builder and
stateIn
like the example shown here.
s

spierce7

02/28/2021, 4:00 AM
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.
3 Views