Skip to content

Instantly share code, notes, and snippets.

@tunjid
Last active January 7, 2022 13:28
Show Gist options
  • Save tunjid/8a73c5c59af242aeba1ee20aa7d560a2 to your computer and use it in GitHub Desktop.
Save tunjid/8a73c5c59af242aeba1ee20aa7d560a2 to your computer and use it in GitHub Desktop.
/**
* Every toggle isExpanded == null should be processed, however every specific request to
* expand or collapse, should be distinct until changed.
*/
private fun Flow<Action.ToggleFilter>.filterToggleMutations(): Flow<Mutation<State>> =
map { it.isExpanded }
.scan(listOf<Boolean?>()) { emissions, isExpanded ->
(emissions + isExpanded).takeLast(2)
}
.transformWhile { emissions ->
when {
emissions.isEmpty() -> Unit
emissions.size == 1 -> emit(emissions.first())
else -> {
val (previous, current) = emissions
if (current == null || current != previous) emit(current)
}
}
true
}
.map { isExpanded ->
Mutation {
copy(queryState = queryState.copy(expanded = isExpanded ?: !queryState.expanded))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment