LoginSignup
6
5

More than 1 year has passed since last update.

Kotlin Coroutineを使ったタイムアウト付きのリトライ処理の方法

Last updated at Posted at 2022-09-15

KotlinCoroutineを使ったタイムアウト付きのリトライ処理の方法

APIリクエスト失敗時にタイムアウト付きでリトライする場合

main.kt

class ApiService() {

    //通信処理用スコープ
    private val ioScope by lazy { CoroutineScope(Job() + Dispatchers.IO) }

    suspend fun request(): Boolean {
        return try {

            //通信するため、IOスコープに切り替える
            withContext(ioScope.coroutineContext) {
                //Timeoutを設定
                //Timeout時はTimeoutCancellationExceptionが吐かれる
                withTimeout(10 * 1000) {

                    //リクエスト結果
                    var result = false

                    while(!result) {
                        //ここでリクエスト
                        result = RequestApi()
                        //1秒後にリトライ
                        delay(1000)
                    }

                    return@withTimeout result

                }

            }

        } catch(ex: Exception) {
            when(ex) {
                is TimeoutCancellationException -> {
                    //タイムアウト時
                }
                else-> {
                    //その他エラー
                }
            }
            false
        }        
    }
    
}

6
5
3

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
6
5