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

Was this helpful?