File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/exceptionhandling Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments