μ λ€λ¦ ꡬ쑰체 | μ€μ²©λ 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