Hi everyone, How would one model the fact that an ...
# flow
j
Hi everyone, How would one model the fact that an item emitted by a flow might be the first this flow has emitted? Basically, when the app starts, we begin collecting a flow for display usage. But we want to detect and react differently for the first item. I've been struggling really hard all afternoon to avoid a
private var hasFirstBeenEmitted : Boolean = false
at class level Is there anyway to stay within the confines of flows? Can provide more details on the implementation if it's too vague and it helps 🙂
c
Why do you want to know if it is the first one?
j
app does indoor wayfinding (think waze but indoor really) when the app starts, we also start our indoor location sdk which may provide a location after about 10sec and is modeled as a shared flow we want to display a blue dot of the user based on it's indoor location so the shared flow is
stateIn
a view model and the blue dot is continuously updated on the map the first location means we have managed to find the user indoor and want to display a one time thing to let them acknowledge that fact hopefully that answers your question 😉
c
Since it's a shared flow, you can collect it multiple times, so I would do something like:
Copy code
viewModelScope.launch {
    val first = yourFlow.first()
    toaster.show("The very first value is $first") // or whatever the first thing you want to do is
}
🙏 1
j
Sorry for not getting back to you! First of all, thanks for the answer 🙂 Might be a dumb question, but
first
documentation mentions the fact that it will cancel the flow collection... isn't that going to cancel all other subscription to the shared flow? Or am I confusing things?
c
Hm, you're right, I'm surprised a
SharedFlow
can be closed. I can't find any way to do it right off my head then 😓
j
that documentation is confusing me tbh 😅 I did gave it a try and it seemed to work, I was able to wait for a first location and my blue dot was still updated on the map which means the shared flow is not completely cancelled... the collection canceled might be referring to the specific collection of first?
c
That's what I thought, but I tested it in the playground and it killed the other
collect
as well 🤔
😞 1