Ich bin mit Kotlin Koroutinen für Netzwerkanforderung Klasse wie diese von der Seite ruft dann Wie Backoff auf Kotlin wiederholen exponentiellen Koroutinen
public suspend fun <T : Any> Call<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>?, response: Response<T?>) {
if (response.isSuccessful) {
val body = response.body()
if (body == null) {
continuation.resumeWithException(
NullPointerException("Response body is null")
)
} else {
continuation.resume(body)
}
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
// Don't bother with resuming the continuation if it is already cancelled.
if (continuation.isCancelled) return
continuation.resumeWithException(t)
}
})
registerOnCompletion(continuation)
}
}
in der Nachrüstung mit Erweiterung Methode aufrufen i wie dieses
obige Verfahren verwende
private fun getArticles() = launch(UI) {
loading.value = true
try {
val networkResult = api.getArticle().await()
articles.value = networkResult
}catch (e: Throwable){
e.printStackTrace()
message.value = e.message
}finally {
loading.value = false
}
}
Ich möchte diesen API-Aufruf in einigen Fällen exponentiell wiederholen ie (IOException) wie kann ich es erreichen ??
wow sehr saubere Antwort danke –
Das war etwas, das mir im Hinterkopf lag einige Tage jetzt. Schön zu sehen, dass die Lösung nicht komplexer ist als das, was ich mir vorgestellt habe. Ich fragte mich auch, ob es sinnvoll wäre, diese Hilfsfunktion als Inline-Funktion zu definieren. Und last but not least: Wie sollte das a modifiziert werden, wenn Sie den Wiederholungsversuch nur nach Aufforderung des Benutzers (zB in einem Dialog) durchführen wollen? –
Auch so viel sauberer als die Rx-Lösung: -O – kenyee