티스토리 뷰

728x90
반응형

Combining Operators 중 대표적인 두가지를 살펴보자 

 

[ 1 ] withLatestFrom 

ObservableType extension에 가보면 

public func withLatestFrom<SecondO: ObservableConvertibleType>(_ second: SecondO) -> Observable<SecondO.E> {
    return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 })
}

이렇게 구현되어있다 

 

 

어떤 옵져버블 뒤에 withLatestFrom(Observable) 해주면 어떤 옵져버블의 이벤트가 발행될때마다 매개변수로 넘겨준 observable의 the latest element를 얻는다 

예제를 보는 게 이해가 빠르다 --! 

 

 

let button = PublishSubject<Void>()
let textField = PublishSubject<String>()

// button 이벤트가 발행될때마다 매개변수로 넘겨준 textField observable의 the latest element를 얻는다
let observable: Observable<String> = button.withLatestFrom(textField)

observable.subscribe(onNext: {
    print($0)
})

textField.onNext("Par")
button.onNext(())
textField.onNext("Pari")
textField.onNext("Paris")

button.onNext(())
button.onNext(())

// 출력값

Par
Paris
Paris

 

 

withLatestFrom 순서를 거꾸로 해보면..ㅎㅎ

// textField 이벤트가 발행될때마다 button Observable의 가장 최근의 값을 얻는다 
let observable: Observable<Void> = textField.withLatestFrom(button)

observable.subscribe(onNext: {
    print($0)
})

textField.onNext("Par")
button.onNext(())
textField.onNext("Pari")
textField.onNext("Paris")

button.onNext(())
button.onNext(())

// 출력값

()
()

 

 

[ 2 ] combineLatest

let left = PublishSubject<Int>()
let right = PublishSubject<Int>()

let observable = Observable.combineLatest(left, right, resultSelector: {
    lastLeft, lastRight in
    "\(lastLeft) \(lastRight)"
})

observable.subscribe(onNext: {
    print($0)
})

left.onNext(1)
right.onNext(4)
right.onNext(5)
left.onNext(2)
right.onNext(6)
left.onNext(3)

// 출력값 

1 4
1 5
2 5
2 6
3 6

 

 

 

Reference 

RayWenderlich - RxSwift

728x90
반응형
댓글
댓글쓰기 폼