Skip to content

Instantly share code, notes, and snippets.

@gabrielbmoro
Created July 12, 2022 22:13
Show Gist options
  • Save gabrielbmoro/5947ed3dfbe91ff6a9cfbcdcecdf1127 to your computer and use it in GitHub Desktop.
Save gabrielbmoro/5947ed3dfbe91ff6a9cfbcdcecdf1127 to your computer and use it in GitHub Desktop.
Typing a Text
ComposableFunction() {
DisposableEffect(Unit) {
typingTimer = TypingTimer().apply {
setup(
baseMessage = welcomingMessage,
finishCallback = { showFooter = true },
currentMessageUpdateCallback = {
// here if you are using viewbinding it could be textView.text = currentMessage
currentMessage = it
}
)
}
onDispose {
releaseTimer()
}
}
}
package com.matematicasimples.presentation.common.components
import android.os.CountDownTimer
import kotlin.math.roundToInt
private const val TYPING_TOTAL_TIME = 10_000L
private const val TYPING_TICK = 100L
class TypingTimer : CountDownTimer(
TYPING_TOTAL_TIME, TYPING_TICK
) {
private var baseMessage: String = ""
private var currentMessageUpdateCallback: ((String) -> Unit)? = null
private var finishCallback: (() -> Unit)? = null
var isRunning: Boolean = false
private set
fun setup(
baseMessage: String,
currentMessageUpdateCallback: ((String) -> Unit),
finishCallback: (() -> Unit)
) {
this.baseMessage = baseMessage
this.currentMessageUpdateCallback = currentMessageUpdateCallback
this.finishCallback = finishCallback
start()
isRunning = true
}
override fun onTick(p0: Long) {
val currentTimestamp = TYPING_TOTAL_TIME - p0
val currentPercentageTimestamp = currentTimestamp.div(TYPING_TOTAL_TIME.toFloat())
val messageMaxIndex = (currentPercentageTimestamp * baseMessage.length).roundToInt()
val message = baseMessage.substring(0, messageMaxIndex)
currentMessageUpdateCallback?.invoke(message)
}
override fun onFinish() {
isRunning = false
currentMessageUpdateCallback?.invoke(baseMessage)
finishCallback?.invoke()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment