Skip to content

Commit 201a368

Browse files
gnefedevmichaelbull
authored andcommitted
Add retryIf function
Facilitates creating a RetryPolicy that only retries if the failure matches a given predicate.
1 parent 16c03b0 commit 201a368

File tree

2 files changed

+65
-0
lines changed
  • src

2 files changed

+65
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.github.michaelbull.retry.policy
2+
3+
import com.github.michaelbull.retry.ContinueRetrying
4+
import com.github.michaelbull.retry.RetryFailure
5+
import com.github.michaelbull.retry.RetryInstruction
6+
import com.github.michaelbull.retry.StopRetrying
7+
8+
/**
9+
* Creates a [RetryPolicy] that returns an [instruction][RetryInstruction] to
10+
* [ContinueRetrying] if the [RetryFailure] satisfies the given [predicate],
11+
* or an [instruction][RetryInstruction] to [StopRetrying] if it doesn't.
12+
*/
13+
inline fun <E> retryIf(crossinline predicate: RetryFailure<E>.() -> Boolean): RetryPolicy<E> = {
14+
if (predicate(this)) {
15+
ContinueRetrying
16+
} else {
17+
StopRetrying
18+
}
19+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.github.michaelbull.retry.policy
2+
3+
import com.github.michaelbull.retry.retry
4+
import kotlinx.coroutines.ExperimentalCoroutinesApi
5+
import kotlinx.coroutines.test.runBlockingTest
6+
import org.junit.jupiter.api.Assertions.assertEquals
7+
import org.junit.jupiter.api.Test
8+
import org.junit.jupiter.api.assertThrows
9+
10+
@ExperimentalCoroutinesApi
11+
class RetryIfTest {
12+
13+
private val retryIllegalState = retryIf<Throwable> {
14+
reason is IllegalStateException
15+
}
16+
17+
@Test
18+
fun `retry with filter should retry specified exception`() = runBlockingTest {
19+
var attempts = 0
20+
21+
retry(limitAttempts(5) + retryIllegalState) {
22+
attempts++
23+
if (attempts < 5) {
24+
throw IllegalStateException()
25+
}
26+
}
27+
28+
assertEquals(5, attempts)
29+
}
30+
31+
@Test
32+
fun `retry with filter should not retry unspecified exception`() = runBlockingTest {
33+
var attempts = 0
34+
35+
assertThrows<UnsupportedOperationException> {
36+
retry(limitAttempts(5) + retryIllegalState) {
37+
attempts++
38+
if (attempts < 5) {
39+
throw UnsupportedOperationException()
40+
}
41+
}
42+
}
43+
44+
assertEquals(1, attempts)
45+
}
46+
}

0 commit comments

Comments
 (0)