Skip to content

Instantly share code, notes, and snippets.

@ankittlp
Created May 22, 2022 16:45
Show Gist options
  • Save ankittlp/dd169b99eece7ce8876a7b06157a5a46 to your computer and use it in GitHub Desktop.
Save ankittlp/dd169b99eece7ce8876a7b06157a5a46 to your computer and use it in GitHub Desktop.
CombineStreamFail_HowToOverCome
// Example of One-Shot piblisher with Stream Failure.
// As we find the value 0 in the stream, we throw an error. This error is eventually catched and replaced with Just(-1) publisher.
// But after a failed value will activates the catch operator and the pipeline will cease to react further.
struct SimpleError: Error {}
let numbers = [5, 4, 3, 2, 1, 0, 9, 8, 7, 6]
let cancellable = numbers.publisher
.tryMap({ val in
guard val != 0 else {throw SimpleError()}
return val
})
.catch({ (error) in
Just(-1)
})
.sink { print("\($0)") }
// To continue with the stream to respond and handle error on emmited value we'll be using combination of flatMap with catch.
// Uncomment this and comment out above pipeline. We'll see the even after getting 0 value which is replaced with -1, our pipeline continue to respond.
/*
let cancellable = numbers.publisher
.flatMap({ val in
Just(val).tryMap({
guard $0 != 0 else {throw SimpleError()}
return $0
})
.catch({ (error) in
Just(-1)
})
})
.sink { print("\($0)") }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment