Publishers.ReplaceEmpty

์ œ๋„ค๋ฆญ ๊ตฌ์กฐ์ฒด | ๋น„์–ด ์žˆ๋Š” ์ŠคํŠธ๋ฆผ์„ ์ œ๊ณต๋œ ์š”์†Œ๋กœ ๊ต์ฒดํ•˜๋Š” Publisher

์ด๋‹ˆ์…œ๋ผ์ด์ €๋Š” ๋‘ ๊ฐœ์˜ ์ธ์ž๋ฅผ ๋ฐ›๋Š”๋‹ค.

  • upstream : ์ƒ์œ„์— ํ๋ฅด๋Š” Publisher

  • output : ์ƒ์œ„์— ํ๋ฅด๋Š” Publisher๊ฐ€ ์–ด๋– ํ•œ ์š”์†Œ๋„ ์ „๋‹ฌํ•˜์ง€ ์•Š๊ณ  ์ข…๋ฃŒํ•  ๋•Œ ์ „๋‹ฌํ•  ์š”์†Œ

์ƒ์œ„ Publisher๊ฐ€ ์ฆ‰์‹œ ์ข…๋ฃŒํ•˜๋Š” Empty์™€ ๊ฐ™์€ ๊ฒƒ์ด๋‚˜ ์‹œํ€€์Šค๊ฐ€ ๋น„์–ด ์žˆ๋Š” Publishers.Sequence ๋“ฑ์ธ ๊ฒฝ์šฐ์— ํ•ด๋‹น Publisher์— ๋ช…์‹œ๋œ ๊ฐ’์œผ๋กœ ๊ต์ฒดํ•œ๋‹ค.

๊ฐ’์„ ๋‚ด์ง€ ์•Š๊ณ  ์ข…๋ฃŒํ•˜๋Š” Publisher๊ฐ€ ํŠน์ • ๊ฐ’์„ ๋‚ด๊ณ  ์ข…๋ฃŒํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

replaceEmpty ์˜คํผ๋ ˆ์ดํ„ฐ์™€ ๊ด€๋ จ์ด ์žˆ๋‹ค.

// Publishers.ReplaceEmpty Publisher
Publishers.ReplaceEmpty(upstream: Publishers.Sequence<[Int], Never>(sequence: []), output: 0)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine ReplaceEmpty Error")
    case .finished:
      print("Combine ReplaceEmpty Finish")
    }
  }, receiveValue: { value in
    print("Combine ReplaceEmpty : \(value)")
  })
  .store(in: &cancellables)

// replaceEmpty Operator
Publishers.Sequence<[Int], Never>(sequence: [])
  .replaceEmpty(with: 0)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine ReplaceEmpty Error")
    case .finished:
      print("Combine ReplaceEmpty Finish")
    }
  }, receiveValue: { value in
    print("Combine ReplaceEmpty : \(value)")
  })
  .store(in: &cancellables)

// Combine ReplaceEmpty : 0
// Combine ReplaceEmpty Finish

์œ„์˜ ์ฝ”๋“œ ๋ชจ๋‘ Publishers.Sequence Publisher์— ๋นˆ ๋ฐฐ์—ด์„ ๋„ฃ์–ด ๊ฐ’์„ ๋‚ด์ง€ ์•Š๊ณ  ์ข…๋ฃŒํ•˜๋Š” Publisher๋ฅผ ๋งŒ๋“ ๋‹ค.

replaceEmpty์— ์˜ํ•ด ์ด Publisher๋Š” ์ฃผ์–ด์ง„ ๊ฐ’์œผ๋กœ ๋Œ€์ฒด๋  ์ˆ˜ ์žˆ๋‹ค.

RxSwift

ifEmpty ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

Observable.from([])
  .ifEmpty(default: 0)
  .subscribe(onNext: { value in
    print("RxSwift ReplaceEmpty : \(value)")
  }, onError: { _ in
    print("RxSwift ReplaceEmpty Error")
  }, onCompleted: {
    print("RxSwift ReplaceEmpty Finish")
  })
  .disposed(by: disposeBag)

// RxSwift ReplaceEmpty : 0
// RxSwift ReplaceEmpty Finish

ReactiveSwift

ํ•ด๋‹น ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š๋Š”๋‹ค.

์ฐธ๊ณ 

ReactiveX - Operators - DefaultIfEmpty

Last updated

Was this helpful?