How can I execute a piece of code once per `userId...
# coroutines
z
How can I execute a piece of code once per
userId
in a
Flow<State>
where the
userId
changes over time?
Copy code
data class State(
    val userId: String, // the current user may change over time
    val isHungry: Boolean, // user may become hungry over time
    val currentTime: Int // hot code path, changes frequently
)

fun CoroutineScope.handleFirstStateForGoodPeople(states: Flow<State>) {
    states
        // when EACH user has `isHungry==true`
        // I want to call a function
        // but only the FIRST time this state is reached PER user (distinct by `userId`)
        .onEachInternal { state -> callSomeFunction() }
        .launchIn(this)
}
b
Anyway you need to implement
distinct
then it will be
states.filter { it.isHungry }.distinctBy { it.user }