Tunko Development Diary

RxSwift) Transforming Operators (combineLatest, zip) 본문

Development/RxSwift

RxSwift) Transforming Operators (combineLatest, zip)

Tunko 2022. 6. 4. 20:47

combineLatest

combineLastest는 2개부터 8개까지 옵저버블을 파라미터로 받고, 클로저를 리턴합니다.

combineLastest에서 중요한건 이벤트가 방출되는 시점입니다.

let disposeBag = DisposeBag()
let emoticonSubject = PublishSubject<String>()
let textSubject = PublishSubject<String>()

Observable.combineLatest(emoticonSubject, textSubject) { emoticon, text -> String in
    return "\\(emoticon) : \\(text)"
}
.subscribe{ print($0)}
.disposed(by: disposeBag)

emoticonSubject.onNext("🍎") // 1
textSubject.onNext("apple")  // 2
textSubject.onNext("apple2") // 3
emoticonSubject.onNext("🍇 not apple") // 4
textSubject.onNext("not grap")
textSubject.onNext("grap")
emoticonSubject.onNext("🍇")
emoticonSubject.onCompleted()
emoticonSubject.onNext("🍌")
textSubject.onCompleted()

출력

next(🍎 : apple)
next(🍎 : apple2)
next(🍇 not apple : apple2)
next(🍇 not apple : not grap)
next(🍇 not apple : grap)
next(🍇 : grap)
completed

출력 결과를 확인해보면 next 이벤트를 처음 emoticonSubject.onNext("🍎") 했을때 발생하지 않는다.

combineLatest으로 전달된 textSubject 에서도 next 이벤트가 발생해야지만 이벤트가 전달됩니다.

 

zip

zip 연산자는 combineLatest 와 거의 흡사합니다. 하지만 방출되는 이벤트는 결과는 다릅니다.

let disposeBag = DisposeBag()
let emoticonSubject = PublishSubject<String>()
let textSubject = PublishSubject<String>()

Observable.zip(emoticonSubject, textSubject) { emoticon, text -> String in
    return "\\(emoticon) : \\(text)"
}
.subscribe{ print($0)}
.disposed(by: disposeBag)

emoticonSubject.onNext("🍎")
textSubject.onNext("apple")
textSubject.onNext("apple2")
emoticonSubject.onNext("🍇 not apple")
textSubject.onNext("not grap")
textSubject.onNext("grap")
emoticonSubject.onNext("🍇")
emoticonSubject.onCompleted()
emoticonSubject.onNext("🍌")
textSubject.onCompleted()

출력

next(🍎 : apple)
next(🍇 not apple : apple2)
next(🍇 : not grap)
completed

결과를 보면 두개의 옵저버블에서 이벤트 순서대로 묶인후 방출됩니다.

반응형
Comments