Publishers.Catch

์ œ๋„ค๋ฆญ ๊ตฌ์กฐ์ฒด | ์‹คํŒจํ•˜๋Š” 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

Last updated

Was this helpful?