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