Android Kotlin: Make view class pass after it’s finished to work

The Handler is of no use when you are using coroutines.

The delay() should be used to delay the execution, and you don’t need to push Runnable to the thread again and again.

class TypeWriterView: AppCompatTextView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    suspend fun commence(txt: CharSequence?, delayMs: Long) {
        if (txt == null) return

        var index = 0
        while (index < txt.length) {
            text = txt.subSequence(0, ++index)

    // Get [Job] reference after launching in [owner]
    fun commenceOnLifecycle(owner: LifecycleOwner, txt: CharSequence?, delayMs: Long): Job =
            owner.lifecycleScope.launch { commence(txt, delayMs) }

LifecycleOwner is implemented by Activity, Fragment, etc. whichever has a lifecycle attached (more info: LifecycleOwner), it dispatches job to Dispatchers.Main by default so UI can be changed.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top