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

zak.taccardi

04/08/2020, 12:16 AM
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

bezrukov

04/08/2020, 6:21 AM
Anyway you need to implement
distinct
then it will be
states.filter { it.isHungry }.distinctBy { it.user }
3 Views