์ค๋์ observable ๋ฐ์ดํฐ๋ฅผ ๊ฐ๊ณตํ๋ operator์ ๋ํด ์ดํด๋ณด๊ฒ ์ต๋๋ค.
1) Map
Observerble์ ์ํด ๋ฐฉ์ถ๋๋ ์์ดํ ๋ค์ ๋ํด ๊ฐ๊ฐ ํจ์๋ฅผ ์ ์ฉํ์ฌ ๋ณํํฉ๋๋ค.
map์ ์ฌ์ฉํ๋ ์์์ ๋๋ค.
let ob = Observable.of("1", "2", "3", "4")
ob.map { Int($0)! }
.subscribe(onNext: { item in
print(item)
}).disposed(by: disposeBag)
//์ถ๋ ฅ
//1
//2
//3
//4
stringํ์ ์ observable์ map operator๋ฅผ ํตํด ๋ชจ๋ item์ Int ํ์ ์ผ๋ก ์บ์คํ ํด์ฃผ์์ต๋๋ค.
2) FlatMap
flatMap์ map๊ณผ๋ ๋ค๋ฅด๊ฒ ์คํธ๋ฆผ์์ ๋ฐฉ์ถ๋๋ ์์ดํ ๋ค์ ๋ค๋ฅธ observable๋ก ๋ง๋ญ๋๋ค.
๊ทธ๋ฌ๋ฏ๋ก flatMap์ ๋ฆฌํด๊ฐ์ ์์ฑ๋ observable์ ๋๋ค.
์์๋ฅผ ๋ณด๊ฒ ์ต๋๋ค.
button.rx.tap
.flatMap { void -> Observable<[String]> in
return fetchAllAnswers()
}.subscribe(onNext: { str in
item.value = str
}).disposed(by: disposeBag)
func fetchAllAnswers() -> Observable<[String]> {
let api = Observable.create { (obsever: AnyObserver<[String]>) -> Disposable in
let answers = API.allAnswers()
obsever.onNext(answers)
obsever.onCompleted()
return Disposables.create()
}
return api
}
๋ฒํผ์ ํด๋ฆญํ์ ๋, ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ fetchAllAnswers() ํจ์๋ฅผ ์คํํด ๊ฐ์ ๋ฐ์ํ๋ ์ฝ๋์ ๋๋ค.
3) Scan
์ด์ ์ ๋ฐฉ์ถ๋ ์์ดํ ๊ณผ ์๋ก ๋ฐฉ์ถ๋ ์์ดํ ์ ๊ฒฐํฉํด ํ์ฌ ์์ดํ ์ ์์ฑํฉ๋๋ค.
์์ ์ฝ๋์ ๋๋ค.
Observable.of(1,2,3,4,5)
.scan(0) { (prevValue, newValue) in
return prevValue + newValue
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
// ์ถ๋ ฅ
// 1
// 3
// 6
// 10
// 15
scan์ ํ์ฉ
1. ๋ฒํผ ์ํ ๋ณ๊ฒฝ
myButton.rx.tap
.scan(false) { (lastState, newValue) in
!lastState
}
.bind(to: requestMoreButton.rx.isSelected)
.disposed(by: disposeBag)
2. ํ์ด๋จธ ๊ฐ 1 ์ฆ๊ฐ
myButton.rx.tap
.scan(0) { (lastCount, newValue) in
lastCount + 1
}
.subscribe(onNext: { print(“taps: \($0)”) })
.disposed(by: disposeBag)
์ฐธ๊ณ : https://jusung.github.io/scan/
4) reduce
scan๊ณผ ๋ฌ๋ฆฌ ๋ง์ง๋ง์ ๋ค ๋ํ ๊ฐ์ ํ๋ฒ๋ง ๋ฐฉ์ถํฉ๋๋ค.
์์
Observable.of(1,2,3,4,5).reduce(0,accumulator: +)
.subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)
'IOS๐ > RxSwift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[RxSwift] Filtering Operator (distinctUntilChanged) (0) | 2022.05.10 |
---|---|
[RxSwift] Error Handling Operator (0) | 2022.05.10 |
[RxSwift] Schedular๋ (subscribeOn, observeOn) (0) | 2022.04.29 |
[RxSwift] Signal, ControlProperty, ControlEvent ๋ ? (0) | 2022.03.21 |
[RxSwift] Driver๋ ? (feat. bind) (0) | 2022.03.21 |
๋๊ธ