ネットで探してもわかりやすいのが見つからなかったのでざっくりまとめ
出会ったエラー
コルーチンを使おうとしたらエラー
suspend function 'mySuspendFunction' should be called only from a coroutine or another suspend function
訳:susupend付きの関数はコルーチン、もしくはほかのsuspend付きの関数から呼ぶべし
コルーチンの中でUIを更新したらエラー
Only the original thread that created a view hierarchy can touch its views.
訳:Viewをいじるのは大元のスレッドでやってくんね?
こんな感じで回避
private fun functionCaller(){
// コルーチンの開始はこれ
GlobalScope.launch {
mySuspendFunction()
}
}
private suspend fun mySuspendFunction() = withContext(Dispatchers.IO) {
/*
コルーチンを使いたくなる長い処理
*/
// UIの更新はUIスレッドで行う必要がある。
runOnUiThread {
myUiText.text = valueMadeInThisFunction
}
}