Publishers.Collect

μ œλ„€λ¦­ ꡬ쑰체 | μ•„μ΄ν…œμ„ μΌμ‹œμ μœΌλ‘œ κΈ°μ–΅ν•˜λŠ” Publisher

μ΄λ‹ˆμ…œλΌμ΄μ €λŠ” ν•œ 개의 인자λ₯Ό λ°›λŠ”λ‹€.

  • upstream : μƒμœ„μ— 흐λ₯΄λŠ” Publisher

값을 받을 λ•Œλ§ˆλ‹€ λ™μž‘ν•˜μ§€ μ•Šκ³ , μ—λŸ¬ λ˜λŠ” μ’…λ£Œ μ΄λ²€νŠΈκ°€ λ‚  λ•ŒκΉŒμ§€ 값을 κΈ°μ–΅ν•΄ λ‘μ—ˆλ‹€κ°€ λ°°μ—΄μ˜ ν˜•νƒœλ‘œ 값을 ν•œκΊΌλ²ˆμ— λ‚Έλ‹€.

μ—λŸ¬λ₯Ό λ‚΄λ©΄ κ·Έ μ‹œμ κΉŒμ§€ λͺ¨μ•„ 놓은 κ°’λ“€ λŒ€μ‹  μ—λŸ¬λ₯Ό λ‚Έλ‹€.

μ’…λ£Œλ₯Ό λ‚΄λ©΄ κ·Έ μ‹œμ κΉŒμ§€ λͺ¨μ•„ 놓은 값듀을 λ°°μ—΄μ˜ ν˜•νƒœλ‘œ ν•œκΊΌλ²ˆμ— λ‚Έλ‹€.

collect μ˜€νΌλ ˆμ΄ν„°μ™€ 관련이 μžˆλ‹€.

let subject = PassthroughSubject<Int, Error>()

// Publishers.Collect Publisher
 Publishers.Collect(upstream: subject)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine Collect Error")
    case .finished:
      print("Combine Collect Finish")
    }
  }, receiveValue: { value in
    print("Combine Collect : \(value)")
  })
  .store(in: &cancellables)

// collect Operator
subject
  .collect()
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine Collect Error")
    case .finished:
      print("Combine Collect Finish")
    }
  }, receiveValue: { value in
    print("Combine Collect : \(value)")
  })
  .store(in: &cancellables)

// 1
subject.send(1)
subject.send(2)
subject.send(completion: .finished)

// Combine Collect : [1, 2]
// Combine Collect Finish

// 2
subject.send(1)
subject.send(completion: .failure(error))

// Combine Collect Error

1의 경우 μ™„λ£Œ 이벀트λ₯Ό λ‚΄κΈ°κΉŒμ§€ μ „λ‹¬λœ 1, 2의 값이 λ°°μ—΄μ˜ ν˜•νƒœλ‘œ λ¬Άμ—¬ ν•œλ²ˆμ— λ°œν–‰λœλ‹€.

2의 경우 μ—λŸ¬λ‘œ 인해 μ’…λ£Œν–ˆκΈ° λ•Œλ¬Έμ— 결과적으둜 μ—λŸ¬λ₯Ό λ‚Έλ‹€.

RxSwift

toArray μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•  수 μžˆλ‹€.

let subject = PublishSubject<Int>()

subject
  .toArray()
  .subscribe(onSuccess: { value in
    print("RxSwift Collect : \(value)")
  }, onError: { _ in
    print("RxSwift Collect Error")
  })
  .disposed(by: disposeBag)

subject.onNext(1)
subject.onNext(2)
subject.onCompleted()

// RxSwift Collect : [1, 2]

ReactiveSwift

collect μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•  수 μžˆλ‹€.

let property = MutableProperty<Int>(0)

property.signal
  .collect()
  .observe { event in
    switch event {
    case let .value(value):
      print("ReactiveSwift Collect : \(value)")
    case .failed:
      print("ReactiveSwift Collect Error")
    case .completed:
      print("ReactiveSwift Collect Finish")
    default:
      break
    }
  }

property.value = 1
property.value = 2

// ReactiveSwift Collect : [1, 2]
// ReactiveSwift Collect Finish

μ°Έκ³ 

ReactiveX - Operators - To

Last updated