Created
July 12, 2022 22:13
-
-
Save gabrielbmoro/5947ed3dfbe91ff6a9cfbcdcecdf1127 to your computer and use it in GitHub Desktop.
Typing a Text
This file contains hidden or 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
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() | |
} | |
} | |
} |
This file contains hidden or 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
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