Combining
๐งฉ Combining Operators โ ์ฌ๋ฌ ์คํธ๋ฆผ์ โ์กฐํฉโํ๊ธฐ
โTwo (or more) Observables enter, one leaves.โ
Combining ์คํผ๋ ์ดํฐ๋ ๋ค์ Observable์ ํ๋๋ก ํฉ์ณ ํ๋ถํ ์ปจํ ์คํธ๋ฅผ ๋ง๋ค๊ฑฐ๋, ์ด๋ฒคํธ ์์๋ฅผ ์ ์ดํฉ๋๋ค. UIยท๋คํธ์ํนยท๋๊ธฐํ ๋ก์ง์์ ํต์ฌ ๋๊ตฌ๋ก ์ฐ์ ๋๋ค.
1๏ธโฃ ๋ํ Combining ์คํผ๋ ์ดํฐ ํ
merge
์ฌ๋ฌ ์คํธ๋ฆผ ์ด๋ฒคํธ๋ฅผ ๋์์ ๋ฐฉ์ถ
์์ ๋ณด์ฅ X, ์ต๋ ๋์ n๊ฐ ์ ์ด merge(maxConcurrent:)
concat
์ง๋ ฌ ์ฐ๊ฒฐ, ์ ์คํธ๋ฆผ ์๋ฃ ํ ๋ค์ ๊ตฌ๋
์์ ๋ณด์ฅ, back-pressure ์ ์ด ์ฌ์
concatMap
flatMap
+concat
(Transform+์ง๋ ฌ)
๊ฐ ์์โObservable ์ง๋ ฌ ์คํ
combineLatest
๊ฐ ์คํธ๋ฆผ์ ์ต์ ๊ฐ ๊ฒฐํฉ
๋ชจ๋ ์์ค 1๊ฐ ์ด์ ๊ฐ ํ ์์
zip
๋์ผ ์ธ๋ฑ์ค๋ผ๋ฆฌ ์ ์์ฑ
์ง ๋ง์ง ์์ผ๋ฉด ๋๊ธฐ, ๊ฐ์ = ์ต์(stream)
withLatestFrom
ํธ๋ฆฌ๊ฑฐ ์คํธ๋ฆผ์ ์ต์ ํ๋ผ๋ฏธํฐ ์ฃผ์
๋ฒํผ ํญ + ์ต์ ํผ ๊ฐ
sample
์ง์ ์ฃผ๊ธฐ/์คํธ๋ฆผ ์, ์ต์ ๊ฐ ์ํ๋ง
ํด๋ง UI Throttle
amb
๋จผ์ ์ด๋ฒคํธ๋ฅผ ๋ฐ์์ํจ ์คํธ๋ฆผ๋ง ์ฌ์ฉ
๋ ์ด์ค Winner ์ ํ
switchLatest
๋ด๋ถ Observable ์ต์ ๊ฒ๋ง ๊ตฌ๋
flatMapLatest
+ identity
2๏ธโฃ ์ค์ ์ค๋ํซ
A. combineLatest
โ ์ด๋ฉ์ผ & ๋น๋ฐ๋ฒํธ ์ ํจ์ฑ
combineLatest
โ ์ด๋ฉ์ผ & ๋น๋ฐ๋ฒํธ ์ ํจ์ฑObservable.combineLatest(emailValid, passwordValid) { $0 && $1 }
.bind(to: loginButton.rx.isEnabled)
B. merge
โ ๋ค์ค ์ผ์ ๋ฐ์ดํฐ ํตํฉ
merge
โ ๋ค์ค ์ผ์ ๋ฐ์ดํฐ ํตํฉObservable.merge(accelerometer, gyroscope, magnetometer)
.subscribe(onNext: processMotion)
C. zip
โ ํํ ๋คํธ์ํฌ ์์ฒญ ๊ฒฐ๊ณผ ๋งคํ
zip
โ ํํ ๋คํธ์ํฌ ์์ฒญ ๊ฒฐ๊ณผ ๋งคํObservable.zip(api.userInfo(), api.userPosts()) { (user, posts) in
ProfileViewModel(user: user, posts: posts)
}
D. withLatestFrom
โ โ์ ์กโ ๋ฒํผ + ์ต์ ํ
์คํธ
withLatestFrom
โ โ์ ์กโ ๋ฒํผ + ์ต์ ํ
์คํธsendButton.rx.tap
.withLatestFrom(messageField.rx.text.orEmpty)
.filter { !$0.isEmpty }
.bind(to: viewModel.sendMessage)
3๏ธโฃ ์ค๋ฅ ์ ํ ๊ท์น
merge
์ฆ์ ์ ํ(fail-fast) โ ๋ค๋ฅธ ์คํธ๋ฆผ ๊ตฌ๋ ํด์
concat
์ ์คํธ๋ฆผ ์๋ฌ โ ์ ํ & ์ํ์ค ์ข ๋ฃ
combineLatest/zip
์ด๋ ํ๋ ์๋ฌ โ ์ ํ & ์ข ๋ฃ
amb
์ ํ๋ ์คํธ๋ฆผ ์๋ฌ๋ง ๊ณ ๋ ค
์๋ฌ ๋ณต๊ตฌ๋ catchError
, retry
(๋ค์ ์ฅ)๋ก ์ฒ๋ฆฌ.
4๏ธโฃ ์ฑ๋ฅ & ๋ฉ๋ชจ๋ฆฌ ๊ณ ๋ ค
combineLatest
๋ ๊ฐ ์์ค์ ์ต์ ๊ฐ์ ์บ์ โ ํฐ ๊ฐ์ฒด๋ ์ฐธ์กฐ ์ ๋ฌ ormap
์ถ์.merge
๋์์ฑ ๋ฌด์ ํ ์ ์ด๋ฒคํธ ํญ๋ฐ ๊ฐ๋ฅ โmaxConcurrent
์ค์ .zip
์ ์ง ๋ง์ถ๊ธฐ ์ํด ๋ฒํผ ์ฌ์ฉ โ ๋น๋์นญ ์คํธ๋ฆผ ์๋๋ฉด ๋ฉ๋ชจ๋ฆฌ ์ฆ๊ฐ.
5๏ธโฃ ํจํด ๋ณ Best Operator
ํผ ์ ๋ ฅ 2๊ฐ+ ๋ฒํผ ํ์ฑ
combineLatest
์ต์ ์ํ ๊ฒฐํฉ
ํ์ผ AโBโC ์์ฐจ ์ ๋ก๋
concatMap
์ง๋ ฌ ๋ณด์ฅ + ๋ณํ
์๋ฒ1/2 ์ค ๋น ๋ฅธ ์๋ต ์ฌ์ฉ
amb
๋ ์ด์ค ์น์ ์คํธ๋ฆผ ์ฑํ
์ฃผ๊ธฐ์ Heartbeat + ์ค์๊ฐ ์๋ฆผ
merge
์๋ก ๋ ๋ฆฝ ๋์ ์ฒ๋ฆฌ
6๏ธโฃ Mini Quiz
merge
์combineLatest
์ฐจ์ด๋ฅผ ์ด๋ฒคํธ ํจ์ ๊ด์ ์์ ์ค๋ช ํด ๋ณด๋ผ.zip
์ฌ์ฉ ์ ๋ ์์ค์ ์ด๋ฒคํธ ์๋๊ฐ ํฌ๊ฒ ๋ค๋ฅด๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ? ๋์์ฑ ์?withLatestFrom
๊ณผsample
์ ์ฐจ์ด ํ ์ค ์์ฝ.
๋ค์ โถ๏ธ timeBased ๋ก ์ด๋ํด
debounce
,throttle
,timeout
๋ฑ ์๊ฐ ๊ธฐ๋ฐ ์คํผ๋ ์ดํฐ๋ฅผ ์ดํด๋ด ์๋ค. ๐
Last updated