お断り(disclaimer):もちろんこの手順は無保証です。 Androidな本Kotlinな本で勉強してました KotlinでもCoroutineが使えるってので非同期で動かして画面への反映を簡単にできるかなぁ ってので試してみました。 Activityの要素をmain thread以外から書き換えるとruntime errorになっちゃうのでそこはViewModel(LiveData) でObserverパタンを使いました Codeはここです

build.gradleでcoroutineをダンロード

appのbuild.gradleで2行追加

dependencies {
   implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
   implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
}

Layoutを定義する

ここを参考にしてください。

スクリーン

TextViewとButtonの簡単な処理です

ソースを書く

ここにコードを置きました。

こいつは5秒まってから現在時刻を取得するObjectです

{GiantJobs {
    suspend fun  getNowAfterGiantJob(ctx: CoroutineScope) :Deferred<String>{
        return ctx.async {
            Thread.sleep(5000L)
            getNow()
        }
    }

    fun getNow() : String = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().time)

ViewModelのなかで値が変わったらPropertyに反映させます。

class StringViewModel : ViewModel(){
    private  val str : MutableLiveData<String> by lazy {
            MutableLiveData<String>()
    }
    fun getStr() : LiveData<String> {
        return str
    }

    fun updateData() {
        GlobalScope.launch {
            str.postValue(GiantJobs.getNowAfterGiantJob(this).await())
        }
    }
}

onCreateでViewModelを配置して値のObserveとButtonのClick処理を入れ込みました

        var button = findViewById<Button>(R.id.button)
        val model = ViewModelProvider.NewInstanceFactory().create(StringViewModel::class.java)
        model.getStr().observe(this, androidx.lifecycle.Observer {
            dateTextView.text = it
        })
        button.setOnClickListener {
            model.updateData()
        }

これでButton押下後の5秒後の時刻を表示します。