dimsuz
03/16/2022, 2:33 PMif (prevState = 1 && state = 0) onEvent(...)
.
Sometimes this leads me to discovery that I think about the state wrong and I refactor, but sometimes I can't and I ask myself what's the best pattern to detect some thresholds in state changes?
Examples:
• ListColumn has just scrolled past 100 visible item, how to report this to analytics?
• Composable with swipeable
modifier has just finished settling after swipe. How to observe this change from swipeableState.isAnimationRunning
from true
to false
and report it to some other component?log("is animating ${swipeableState.isAnimationRunning}")
val flow = snapshotFlow { swipeableState.isAnimationRunning }
LaunchedEffect(Unit) {
flow.collect {
log("animated changed to ${it}")
}
}
this logs a lot of "is animating" which changes from false
to true
to false
, but "animated changed" is logged only once as start as false
.
So I guess snapshotFlow is not for this usecase or maybe it's even an antipattern here. What's the right way to go then?Zach Klippenstein (he/him) [MOD]
03/16/2022, 2:48 PMUnit
.dimsuz
03/16/2022, 2:52 PMsnapshotFlow
for those cases is a valid way to go?Zach Klippenstein (he/him) [MOD]
03/16/2022, 2:55 PMsnapshotFlow { state }
.distinctUntilChanged()
.drop(1)
.filter { it == 0 }
Or
snapshotFlow { state }
.scan { prev, new ->
prev == 1 && new == 0
}
.distinctUntilChanged()
dimsuz
03/16/2022, 3:07 PMval swipeableState = rememberSwipeableState(initialValue = findInitialAnchorId(state).value)
LaunchedEffect(swipeableState) {
val flow = snapshotFlow { swipeableState.isAnimationRunning }
flow.collect {
Timber.e("animated changed to ${it}")
}
}
This works. I have logged "swipeableState" and it doesn't change object-hex pointer, so it's the same)