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