https://kotlinlang.org logo
#flow
Title
# flow
c

Christian S.

09/18/2020, 7:16 PM
Hello everyone, I am a Kotlin newbie and are looking for a way to resume a Flow after an exception has been thrown by the emitter. I want to adhere to Exception Transparency. I have seen a workaround on SO (https://stackoverflow.com/a/63886110) but wanted to ask if you know an easier / less custom solution. Thanks!
g

gildor

09/20/2020, 3:25 PM
You can use catch operator to handle exception
c

Christian S.

09/21/2020, 8:49 AM
Thanks, Andrey, but my requirement is to not terminate the flow when an exception in the emitter occurs. When the exception is catched with a catch operator the flow still terminates. To solve this, my colleague just had a simple solution: just emit(..) a default/error value in case an exception has occurred in the emitter before and move the emit(..) call outside of the try-block. This adheres to Exception Transparency.
👍🏾 1
g

gildor

09/21/2020, 8:51 AM
But it’s up to flow terminate or not, right? The only what you can do is restart flow
Code from this SO question just should be:
Copy code
.flatMapLatest { fetchSomeData().catch { //any default }
            .onEach { handleData() }
            .collect()
c

Christian S.

09/21/2020, 8:54 AM
What I need(ed) is:
Copy code
flow {
    val result = try {
        // call some REST API and return the result
    } catch (e: Exception) {
        // return some default/error value 
    }
    emit(result)
}
So simple that I felt stupid asking the initial question.
g

gildor

09/21/2020, 9:06 AM
yep, this what I meant, just example from SO returns flow