Wednesday, July 15, 2020

android kotlin - Coroutines delay

MainActivity.kt

package com.example.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // show random numbers periodically
        button.setOnClickListener {
            GlobalScope.launch(Dispatchers.Main) {
                doTask()
            }
        }
    }


    private suspend fun doTask(){
        textView.text = "Random numbers..."

        for (i in 12 downTo 0){
            // delays coroutine for a given time without blocking
            // a thread and resumes it after a specified time
            delay(1000) // time in milliseconds

            // show next random number after delay
            textView.append("\n" + Random.nextInt(500))
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#EDEAE0">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        tools:text="Hello World!"
        style="@style/TextAppearance.MaterialComponents.Headline5"
        app:layout_constraintHorizontal_bias="0.534"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Click Me"
        android:backgroundTint="#4B5320"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle (app) [dependencies]

// kotlin coroutine
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'