Created
January 10, 2024 19:41
-
-
Save Kvest/30f77c55a1138dd2c00676b3a7822bdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setContent { | |
val animationDurationMs = 500 | |
val messageDisplayDurationMs = 1000L | |
var currentMessageNum by remember { mutableStateOf(0) } | |
//----------This part of the code can be easily moved to the presentation layer and exposed as flow--------- | |
// And then the currentMessageNum will look like: val currentMessageNum by state.messages.collectAsStateWithLifecycle() | |
var messageCounter by remember { mutableStateOf(0) } | |
val messagesQueue = remember { Channel<Int>(capacity = Channel.UNLIMITED) } | |
LaunchedEffect(messagesQueue) { | |
launch { | |
while (isActive) { | |
currentMessageNum = messagesQueue.receive() | |
delay(messageDisplayDurationMs) | |
if (messagesQueue.isEmpty) { | |
currentMessageNum = 0 | |
} | |
} | |
} | |
} | |
//------------------- | |
ComposeTestsTheme { | |
Box( | |
modifier = Modifier.fillMaxSize() | |
) { | |
Button( | |
modifier = Modifier.align(Alignment.Center), | |
onClick = { | |
messageCounter = messageCounter.inc() | |
messagesQueue.trySend(messageCounter) | |
} | |
) { | |
Text( | |
text = stringResource(id = R.string.animated_message_send_message) | |
) | |
} | |
AnimatedContent( | |
targetState = currentMessageNum, | |
transitionSpec = { | |
fadeIn(animationSpec = tween(delayMillis = if (this.initialState > 0) animationDurationMs else 0, durationMillis = animationDurationMs)) with | |
fadeOut(animationSpec = tween(durationMillis = animationDurationMs)) | |
}, | |
modifier = Modifier | |
.align(Alignment.Center) | |
.offset(y = 80.dp), | |
) { target -> | |
if (target > 0) { | |
Text( | |
modifier = Modifier | |
.background( | |
color = MaterialTheme.colorScheme.errorContainer, | |
shape = RoundedCornerShape(8.dp) | |
) | |
.padding(horizontal = 15.dp, vertical = 5.dp), | |
text = stringResource(id = R.string.animated_message_message, target), | |
color = MaterialTheme.colorScheme.error | |
) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment