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
์ฐธ๊ณ
Last updated
Was this helpful?