μ λ€λ¦ ꡬ쑰체
μ΄λμ
λΌμ΄μ λ μΈ κ°μ μΈμλ₯Ό λ°λλ€.
upstream
: μμμ νλ₯΄λ Publisher
initialResult
: μ΄κΈ° κ°.
nextPartialResult
: μμμ μ°μμ μΌλ‘ μ μ©ν ν΄λ‘μ
Publisherκ° λ΄λ μμμ μ°μμ μΌλ‘ ν¨μλ₯Ό μ μ©νκ³ μ€νν ν, μ±κ³΅μ μΌλ‘ μ€νλ ν¨μμ λ°ν κ°μ λΈλ€.
Swiftμ reduce
ν¨μμ λμμ΄ λΉμ·νμ§λ§ reduce
κ° μ΅μ’
κ²°κ³Όλ§μ λ°ννλ€λ©΄ scan
μ ν¨μκ° μ μ©λ μμμ λ€μ μμμ λν΄ ν¨μλ₯Ό μ μ©νμ¬ κ° μμκ° μ μ§μ μΌλ‘ λ€μ λ°νλλ€.
scan
μ€νΌλ μ΄ν°μ κ΄λ ¨μ΄ μλ€.
// Publishers.Scan Publisher
Publishers.Scan(upstream: Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3]), initialResult: 0) { $0 + $1 }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Scan Error")
case .finished:
print("Combine Scan Finish")
}
}, receiveValue: { value in
print("Combine Scan : \(value)")
})
.store(in: &cancellables)
// scan Operator
Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3])
.scan(0) { $0 + $1 }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Scan Error")
case .finished:
print("Combine Scan Finish")
}
}, receiveValue: { value in
print("Combine Scan : \(value)")
})
.store(in: &cancellables)
// Combine Scan : 1
// Combine Scan : 3
// Combine Scan : 6
// Combine Scan Finish
μμ Publisherλ 1, 2, 3μ κ°μ μ°¨λ‘λλ‘ λΈλ€. μ μ§μ μΌλ‘ μ΄μ μ κ°κ³Ό νμ¬μ κ°μ λν κ°μ λ°ννλλ‘ νμκ³ , λ€μκ³Ό κ°μ΄ λμνλ€.
1μ΄ μ΄κΈ°κ° 0κ³Ό λν΄μ Έ 1μ κ°μ λΈλ€.
2κ° μ΄μ μ κ° 1κ³Ό λν΄μ Έ 3μ κ°μ λΈλ€.
3μ΄ μ΄μ μ κ° 3κ³Ό λν΄μ Έ 6μ κ°μ λΈλ€.
κ²°κ³Όμ μΌλ‘ 1, 3, 6μ κ°μ μ°¨λ‘λλ‘ λ΄κ³ μ’
λ£νλ€.
RxSwift
scan
μ€νΌλ μ΄ν°λ₯Ό μ¬μ©νμ¬ κ΅¬νν μ μλ€.
Observable.from([1, 2, 3])
.scan(0) { $0 + $1 }
.subscribe(onNext: { value in
print("RxSwift Scan : \(value)")
}, onError: { _ in
print("RxSwift Scan Error")
}, onCompleted: {
print("RxSwift Scan Finish")
})
.disposed(by: disposeBag)
// RxSwift Scan : 1
// RxSwift Scan : 3
// RxSwift Scan : 6
// RxSwift Scan Finish
ReactiveSwift
scan
μ€νΌλ μ΄ν°λ₯Ό μ¬μ©νμ¬ κ΅¬νν μ μλ€.
SignalProducer([1, 2, 3])
.scan(0) { $0 + $1 }
.start { event in
switch event {
case let .value(value):
print("ReactiveSwift Scan : \(value)")
case .failed:
print("ReactiveSwift Scan Error")
case .completed:
print("ReactiveSwift Scan Finish")
default:
break
}
}
// ReactiveSwift Scan : 1
// ReactiveSwift Scan : 3
// ReactiveSwift Scan : 6
// ReactiveSwift Scan Finish
μ°Έκ³
ReactiveX - Operators - Scan