์ ๋ค๋ฆญ ๊ตฌ์กฐ์ฒด | ์ ๋ฌ๋ฐ์ ๋ชจ๋ ์์์ ํด๋ก์ ๋ฅผ ์ ์ฉํ๊ณ , ์์์ ํ๋ฅด๋ Publisher๊ฐ ์ข
๋ฃํ ๋ ์ถ์ ๋ ๊ฐ์ ๋ด๋ Publisher
์ด๋์
๋ผ์ด์ ๋ ์ธ ๊ฐ์ ์ธ์๋ฅผ ๋ฐ๋๋ค.
upstream
: ์์์ ํ๋ฅด๋ Publisher
initial
: ํด๋ก์ ์ ์ฒซ ๋ฒ์งธ ํธ์ถ์ ์ ๊ณต๋๋ ์ด๊ธฐ ๊ฐ
nextPartialResult
: ์๋ก์ด ๊ฐ์ ๋ด๊ธฐ ์ํด ์ด์ ๊น์ง ์ถ์ ๋ ๊ฐ๊ณผ ์์ Publisher์ ๋ค์ ์์๋ฅผ ์ทจํ๋ ํด๋ก์
์์ Publisher๊ฐ ๋ฐฐ์ถํ ํญ๋ชฉ์ ํจ์๋ฅผ ์์๋๋ก ์ ์ฉํ๊ณ ํจ์๋ฅผ ์ฐ์ฐํ ํ ์ต์ข
๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
Swift์ reduce
ํจ์์ ๊ฐ์ ๋์์ ํ๋ค.
์์ Publisher์ ํ๋ฅด๋ ๋ชจ๋ ๊ฐ์ ๋ชจ์ ์ด๋ ํ ํ๋์ ๊ฐ์ ๋ด๊ณ ์ถ์ ๋ ์ฌ์ฉํ ์ ์๋ค.
reduce
์คํผ๋ ์ดํฐ์ ๊ด๋ จ์ด ์๋ค.
// Publishers.Reduce Publisher
Publishers.Reduce(upstream: Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3]), initial: 0) { $0 + $1 }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Reduce Error")
case .finished:
print("Combine Reduce Finish")
}
}, receiveValue: { value in
print("Combine Reduce : \(value)")
})
.store(in: &cancellables)
// reduce Operator
Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3])
.reduce(0) { $0 + $1 }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Reduce Error")
case .finished:
print("Combine Reduce Finish")
}
}, receiveValue: { value in
print("Combine Reduce : \(value)")
})
.store(in: &cancellables)
// Combine Reduce : 6
// Combine Reduce Finish
์์ Publisher๊ฐ 1, 2, 3์ ๊ฐ์ ์ฐจ๋ก๋๋ก ๋ด๋๋ฐ, ์ด๊ธฐ ๊ฐ์ 0์ผ๋ก ํ๊ณ ์ค์ฒฉ๋ ์ด์ ์ ๊ฐ๊ณผ ์๋ก์ด ๊ฐ์ ๋ง์
์ฐ์ฐ์ ํ๋ ํด๋ก์ ๋ฅผ ์ ๊ณตํ์ฌ ์์๋ฅผ ๋ชจ๋ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ๋ด๋๋ก ํ์๋ค.
๊ฒฐ๊ณผ์ ์ผ๋ก 6์ ๊ฐ์ ๋ด๊ณ ์ข
๋ฃํ๋ค.
RxSwift
reduce
์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ ์ ์๋ค.
Observable.from([1, 2, 3])
.reduce(0) { $0 + $1 }
.subscribe(onNext: { value in
print("RxSwift Reduce : \(value)")
}, onError: { _ in
print("RxSwift Reduce Error")
}, onCompleted: {
print("RxSwift Reduce Finish")
})
.disposed(by: disposeBag)
// RxSwift Reduce : 6
// RxSwift Reduce Finish
ReactiveSwift
reduce
์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ ์ ์๋ค.
SignalProducer([1, 2, 3])
.reduce(0) { $0 + $1 }
.start { event in
switch event {
case let .value(value):
print("ReactiveSwift Reduce : \(value)")
case .failed:
print("ReactiveSwift Reduce Error")
case .completed:
print("ReactiveSwift Reduce Finish")
default:
break
}
}
// ReactiveSwift Reduce : 6
// ReactiveSwift Reduce Finish
์ฐธ๊ณ
ReactiveX - Operators - Reduce