Stefan Oltmann
04/25/2024, 9:13 AMval showZoomToastState = remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
val onZoomUserInput: () -> Unit = {
coroutineScope.launch {
showZoomToastState.value = true
delay(ZOOM_TOAST_DURATION_MS)
showZoomToastState.value = false
}
}
Stylianos Gakis
04/25/2024, 9:18 AMvalue class ZoomLevel(value: Float)
val zoomLevelChannel = remember {
MutableSharedFlow<ZoomLevel>(
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
}
val zoomLevelToShow: Float? by remember { mutableFloatStateOf(null) }
... onZoomUserInput = { zoomLevel: Float ->
zoomLevelChannel.tryEmit(ZoomLevel(zoomLevel))
}
...
LaunchedEffect(zoomLevelChannel) {
zoomLevelChannel.collectLatest { zoomLevel ->
zoomLevelToShow = zoomLevel.value
delay(1.seconds)
zoomLevelToShow = null
}
}
if (zoomLevelToShow != null) {
ZoomLevelToast(zoomLevelToShow)
}
Keep the channel as your safe place to put all the events to, and you can safely do a collectLatest on it in a LaunchedEffect, dropping all the previous values since you do not really care about them if there is a new zoom level, and you can control dismissing the dialog after 1 second that there was no event by setting the state back to null afterwards.
-Edited after Albert’s suggestion to use MutableSharedFlow insteadAlbert Chang
04/25/2024, 9:22 AMMutableSharedFlow
, which should be more efficient.
Here’s something similar.Stylianos Gakis
04/25/2024, 9:23 AMcollectLatest
to drop the old (now obsolete) events right?Albert Chang
04/25/2024, 9:28 AMStefan Oltmann
04/25/2024, 9:31 AMval showZoomToastState = remember { mutableStateOf(false) }
val showZoomToastStateFlow = remember {
MutableSharedFlow<Unit>(
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
}
val onZoomUserInput: () -> Unit = {
showZoomToastStateFlow.tryEmit(Unit)
}
LaunchedEffect(showZoomToastStateFlow) {
showZoomToastStateFlow.collectLatest {
showZoomToastState.value = true
delay(ZOOM_TOAST_DURATION_MS)
showZoomToastState.value = false
}
}
Stylianos Gakis
04/25/2024, 9:33 AMshowZoomToastStateFlow
into showZoomToastSharedFlow
, in the variable name, so that you do not confuse yourself or another colleague in the future 😄