๋คํธ์ํฌ ์์ฒญ์ด ์คํจํ์ ๋ ๋ฐ๋ก ์ฌ์ฉ์์๊ฒ ์คํจ๋ฌธ๊ตฌ๋ฅผ ๋์ฐ๋ ๊ฒ๋ณด๋ค 2๋ฒ๋ ์์ฒญํด๋ณด๊ณ ์ฌ์ฉ์์๊ฒ ์คํจ๋ฌธ๊ตฌ๋ฅผ ๋์ฐ๊ฒ ํ ์ ์๋ค. ๋ฐ๋ก retry() ์ฐ์ฐ์๋ฅผ ํตํด์์ด๋ค. retry(2) ๋ฅผ ํตํด ์ฒซ๋ฒ์งธ ์๋ + 2๋ฒ ๋์์ฒญ ํ์์๋ ์คํจํ๋ค๋ฉด catch() ์ฐ์ฐ์๋ฅผ ํตํด ์คํจ ์ด๋ฒคํธ๋ฅผ ์ก์๋ธ๋ค.
enum SampleError: Error {
case somethingWentWrong
}
func fetchData() -> AnyPublisher<String, SampleError> {
let shouldFail = Bool.random()
if shouldFail {
print("Fetching data failed, will retry...")
return Fail(error: SampleError.somethingWentWrong)
.eraseToAnyPublisher()
} else {
return Just("Data loaded successfully")
.setFailureType(to: SampleError.self)
.eraseToAnyPublisher()
}
}
var retryCount = 0
var cancellable = fetchData()
.handleEvents(receiveSubscription: { _ in
// ์ด๊ธฐ ์๋๋ฅผ ์นด์ดํธํ์ง ์๊ณ , ์ฌ์๋ ์์ ์์๋ง ์นด์ดํธ
if retryCount > 0 { print("Retry attempt #\(retryCount)") }
retryCount += 1})
.retry(3) // ์ต๋ 3๋ฒ ์ฌ์๋
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("Completed successfully")
case .failure(let error):
print("Failed after \(retryCount - 1) retries with error: \(error)")
}
}, receiveValue: { value in
print("Received value: \(value)")
})
๋จผ์ retry์ฐ์ฐ์๋ฅผ ์ดํด๋ณด์. retry์์ ์ฃผ์ํ ์ ์ retry(3) ์ ํ๋ฉด 3๋ฒ ์๋ํ๋ ๊ฒ์ด ์๋๋ผ ์ด 4๋ฒ ์๋ํ๋ค! ์ฒซ๋ฒ์งธ ์๋์์ ์คํจํ๋ฉด 3๋ฒ๋ ์๋ํ๋ค๋ ์๋ฏธ์ด๊ธฐ ๋๋ฌธ์ด๋ค.
enum SampleError2: Error {
case somethingWentWrong
}
func fetchData2() -> AnyPublisher<String, SampleError2> {
let shouldFail = Bool.random()
if shouldFail {
return Fail(error: SampleError2.somethingWentWrong)
.eraseToAnyPublisher()
} else {
return Just("Data loaded successfully")
.setFailureType(to: SampleError2.self)
.eraseToAnyPublisher()
}
}
var cancellable2 = fetchData2()
.catch { error -> Just<String> in
print("An error occurred: \(error)")
return Just("Handling error gracefully, returning fallback data.")
}
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("Completed successfully or handled error gracefully.")
case .failure:
print("Should not see this because errors are handled.")
}
}, receiveValue: { value in
print("Received value: \(value)")
})
catch() ์ฐ์ฐ์๋ ๋จ์ด ๊ทธ๋๋ก ๋ค์ด์คํธ๋ฆผ ๊ฐ๊ธฐ์ ์๋น์์ชฝ์์ ์๋ฌ๋ฅผ ์ก์๋ด์ด ๋๋ค๋ฅธ ์คํธ๋ฆผ์ ์ด๊ฑฐ๋ ๊ธฐํ ์ฒ๋ฆฌ๋ฅผ ํด์ค ์ ์๋ ์ฐ์ฐ์์ด๋ค.
https://www.kodeco.com/21773708-intermediate-combine/lessons/5
'๐ฆ Flutter' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
VSCode๊ฐ ํ๋ฌํฐ ํ๋ก์ ํธ ์ธ์์ ๋ชปํ๋ ๋ฌธ์ (0) | 2024.05.19 |
---|---|
ํ๋ฌํฐ ํ๋ก์ ํธ ์คํ์ ์์ดํฐ ์ค๊ธฐ๊ธฐ(or ์๋ฎฌ)๊ฐ ๋์๊ฐ์ง ์๋ ๋ฌธ์ (0) | 2024.05.19 |
| Combine | 11. Mapping Errors (0) | 2024.05.14 |
| Combine | 10. Managing Backpressure (0) | 2024.05.14 |
| Combine | 9. Networking with Combine (0) | 2024.05.14 |