使用改装向服务器发出请求时出错



我一直在开发一个应用程序,需要在服务器上发出一些请求来获取一些数据。这在大多数情况下都很好,但有时我会出错Socket timeoutINTERNAL SERVER ERROR时,应用程序会崩溃。我认为消除这些错误的一种方法是通过以下代码:

var i = 0
while(i == 0){
try{
viewmodel.getRequestFromServer()
i = 1
}catch(e: SocketTimeoutException){
i = 0
}
}

但我必须提出很多请求,这将使代码非常长。有人能给我一个更好的方法吗?非常感谢。

/**
* call in a background thread (better to use RxJava for it)
* */
fun call() {
var attempts = 0
val maxAttempts = 3
val random = Random(1_000)
while (attempts < maxAttempts) {
try {
if (attempts > 0) {
Thread.sleep(random.nextLong())
}
viewmodel.getRequestFromServer()
} catch (e: SocketTimeoutException) {
// do something with the error
} catch (e: InterruptedException) {
// the thread was interrupted
// should return or do something with it
return
} finally {
attempts++
}
}
}