Skip to content

Commit a9eab07

Browse files
Add playground file for retry
1 parent 167cad9 commit a9eab07

File tree

1 file changed

+42
-0
lines changed
  • app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/exceptionhandling

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.lukaslechner.coroutineusecasesonandroid.playground.flow.exceptionhandling
2+
3+
import kotlinx.coroutines.coroutineScope
4+
import kotlinx.coroutines.delay
5+
import kotlinx.coroutines.flow.Flow
6+
import kotlinx.coroutines.flow.catch
7+
import kotlinx.coroutines.flow.flow
8+
import kotlinx.coroutines.flow.retryWhen
9+
import kotlinx.coroutines.launch
10+
11+
suspend fun main(): Unit = coroutineScope {
12+
13+
launch {
14+
stocksFlow()
15+
.catch { throwable ->
16+
println("Handle exception in catch() operator $throwable")
17+
}
18+
.collect { stockData ->
19+
println("Collected $stockData")
20+
}
21+
}
22+
}
23+
24+
private fun stocksFlow(): Flow<String> = flow {
25+
26+
repeat(5) { index ->
27+
28+
delay(1000) // Network call
29+
30+
if (index < 4) {
31+
emit("New Stock data")
32+
} else {
33+
throw NetworkException("Network Request Failed!")
34+
}
35+
}
36+
}.retryWhen { cause, attempt ->
37+
println("Enter retry() with $cause")
38+
delay(1000 * (attempt + 1))
39+
cause is NetworkException
40+
}
41+
42+
class NetworkException(message: String) : Exception(message)

0 commit comments

Comments
 (0)