์ ๋ค๋ฆญ ๊ตฌ์กฐ์ฒด | ์คํจํ๋ Publisher๋ฅผ ๋ค๋ฅธ Publisher๋ก ๊ต์ฒดํ์ฌ ์์์ ํ๋ฅด๋ Publisher๋ก๋ถํฐ ์๋ฌ๋ฅผ ์ฒ๋ฆฌํ๋ Publisher
์ด๋์
๋ผ์ด์ ๋ ๋ ๊ฐ์ ์ธ์๋ฅผ ๋ฐ๋๋ค.
upstream
: ์์์ ํ๋ฅด๋ Publisher
handler
: ์์์ ํ๋ฅด๋ Publisher๊ฐ ์๋ฌ๋ฅผ ๋ด๋ ๊ฒฝ์ฐ ์๋ก์ด Publisher๋ฅผ ๋ง๋๋ ํด๋ก์
์์์ ํ๋ฅด๋ Publisher์ ์๋ก์ด Publisher์ Output ํ์
์ ๋์ผํด์ผ ํ๋ค.
์์ Publisher๊ฐ ์๋ฌ๋ฅผ ๋ด๋ ๊ฒฝ์ฐ ์๋ฌ๋ฅผ ๋ด๋ฉฐ ์ข
๋ฃํ๋ ๋์ ๋ค๋ฅธ Publisher๋ก ๋์ฒดํ๋ค.
catch
์คํผ๋ ์ดํฐ์ ๊ด๋ จ์ด ์๋ค.
// Publishers.Catch Publisher
Publishers.Catch(upstream: Fail(error: error)) { _ in Just("Error") }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Catch Error")
case .finished:
print("Combine Catch Finish")
}
}, receiveValue: {
print("Combine Catch : \($0)")
})
.store(in: &cancellables)
// catch Operator
Fail(error: error)
.catch { _ in Just("Error") }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Catch Error")
case .finished:
print("Combine Catch Finish")
}
}, receiveValue: {
print("Combine Catch : \($0)")
})
.store(in: &cancellables)
// Combine Catch : Error
// Combine Catch Finish
์์ ์ฝ๋๋ ์คํจํ๋ Publisher์ธ Fail
๋ก๋ถํฐ catch
์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ์๋ฌ๋ฅผ ๋ด๊ณ ์ข
๋ฃํ๋ ๋์ Just
Publisher๋ก ๋์ฒดํ๋ค.
RxSwift
catchError
์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ ์ ์๋ค.
Observable.error(error)
.catchError { _ in Observable.just("Error") }
.subscribe(onNext: {
print("RxSwift Catch : \($0)")
}, onError: { _ in
print("RxSwift Catch Error")
}, onCompleted: {
print("RxSwift Catch Finish")
})
.disposed(by: disposeBag)
// RxSwift Catch : Error
// RxSwift Catch Finish
ReactiveSwift
flatMapError
์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ ์ ์๋ค.
SignalProducer(error: error)
.flatMapError { error in SignalProducer(value: "Error") }
.start { event in
switch event {
case let .value(value):
print("ReactiveSwift Catch : \(value)")
case .failed:
print("ReactiveSwift Catch Error")
case .completed:
print("ReactiveSwift Catch Finish")
default:
break
}
}
// ReactiveSwift Catch : Error
// ReactiveSwift Catch Finish
์ฐธ๊ณ
ReactiveX - Operators - Catch