-
Notifications
You must be signed in to change notification settings - Fork 0
/
RetryNetworkRequestViewModel.kt
50 lines (46 loc) · 1.67 KB
/
RetryNetworkRequestViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase6
import androidx.lifecycle.viewModelScope
import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel
import com.lukaslechner.coroutineusecasesonandroid.mock.MockApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber
class RetryNetworkRequestViewModel(
private val api: MockApi = mockApi()
) : BaseViewModel<UiState>() {
fun performNetworkRequest() {
uiState.value = UiState.Loading
viewModelScope.launch {
val numberOfRetries = 2
try {
retry(times = numberOfRetries) {
val recentVersions = api.getRecentAndroidVersions()
uiState.value = UiState.Success(recentVersions)
}
} catch (e: Exception) {
uiState.value = UiState.Error("Network Request failed")
}
}
}
// retry with exponential backoff
// inspired by https://stackoverflow.com/questions/46872242/how-to-exponential-backoff-retry-on-kotlin-coroutines
private suspend fun <T> retry(
times: Int,
initialDelayMillis: Long = 100,
maxDelayMillis: Long = 1000,
factor: Double = 2.0,
block: suspend () -> T
): T {
var currentDelay = initialDelayMillis
repeat(times) {
try {
return block()
} catch (exception: Exception) {
Timber.e(exception)
}
delay(currentDelay)
currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelayMillis)
}
return block() // last attempt
}
}