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