0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Kotlinでコルーチンのエラー回避

Last updated at Posted at 2021-07-16

ネットで探してもわかりやすいのが見つからなかったのでざっくりまとめ

出会ったエラー

コルーチンを使おうとしたらエラー
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
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?