UI Binding
๐๏ธ RxCocoa UI Binding โ From Events to Declarative Updates
"โํ๊น-์ก์ ์ ์๋ , ์ด์ ๋
Rx
์ ํจ๊ป!โ
RxCocoa๋ UIKit ์ปดํฌ๋ํธ์ Reactive extensions๋ฅผ ์ ๊ณตํด ํฐ์นยทํ
์คํธยท์คํฌ๋กค ๋ฑ ์ด๋ฒคํธ ์คํธ๋ฆผ์ ์ฝ๊ฒ ๊ตฌ๋
ํ๊ณ , ์์ฑ์ ๋ฐ์ธ๋ฉํ ์ ์์ต๋๋ค. ์ด ๋ฌธ์์์๋ ๊ฐ์ฅ ๋ง์ด ์ฐ์ด๋ UIButton.rx.tap
, UITextField.rx.text
, UITableView.rx.items
๋ฐ์ธ๋ฉ ํจํด์ ์ ๋ฆฌํฉ๋๋ค.
1๏ธโฃ UIButton โ Reactive Tap
loginButton.rx.tap
.throttle(.milliseconds(500), scheduler: MainScheduler.instance)
.bind(to: viewModel.loginTap)
.disposed(by: bag)
rx.tap
=Observable<Void>
Tap debounce/throttle๋ก ์ค๋ณต ํด๋ฆญ ๋ฐฉ์ง
withUnretained(self) ํ์ฉ ์:
button.rx.tap .withUnretained(self) .subscribe(onNext: { vc, _ in vc.dismiss(animated:true) })
2๏ธโฃ UITextField & UILabel โ Twoโway Binding
// View โ ViewModel
emailField.rx.text.orEmpty
.bind(to: viewModel.email)
.disposed(by: bag)
// ViewModel โ View
viewModel.email
.bind(to: emailField.rx.text)
.disposed(by: bag)
.orEmpty
: Optional String โ String ๋ณํRxCocoa์๋ ๋ด์ฅ๋ ์๋ฐฉํฅ ๋ฐ์ธ๋ฉ ๋์ฐ๋ฏธ๊ฐ ์์ผ๋ฏ๋ก, ๋ณต์กํ ๊ฒฝ์ฐ์๋
BindRelay
๋๋ ์ฌ์ฉ์ ์ ์ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ๊ณ ๋ คํ์ธ์.
3๏ธโฃ UITableView โ items(cellIdentifier:)
A. Simple Static Cell
dataObservable
.bind(to: tableView.rx.items(cellIdentifier: "Cell")) { index, model, cell in
cell.textLabel?.text = model.title
}
.disposed(by: bag)
B. Sectioned Table (RxDataSources)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Item>>(configureCell: ...)
sectionsObservable
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: bag)
RxDataSources
๋ ๋ณ๊ฒฝ ์ฌํญ์ ์ธ์ํ๋animated
์ฒ๋ฆฌ ๋๋ผ์ด๋ฒ๋ฅผ ์ถ๊ฐํฉ๋๋ค.
4๏ธโฃ CollectionView Quick Note
items.bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: MyCell.self)) { row, item, cell in
cell.configure(item)
}.disposed(by: bag)
5๏ธโฃ ControlProperty & Driver
Feature
ControlEvent
ControlProperty
Driver
Source
UI ์ด๋ฒคํธ (tap)
UI ์์ฑ (text)
Any Observable
Error
never
never
never
Scheduler
Main
Main
Main
UI Binding Output์ Driver ๊ถ์ฅ (Main thread, shareReplay(1))
6๏ธโฃ Memory & Thread Safety
RxCocoa๋ ์๋์ผ๋ก MainScheduler์์ ๊ตฌ๋ ํฉ๋๋ค.
๋ฐ์ธ๋ฉ ํ์ฅ ํจ์(
bind(to:)
)๋ ๋์ ๊ฐ์ฒด๊ฐ ํด์ ๋ ๋ ์๋์ผ๋ก dispose๋ฉ๋๋ค.
7๏ธโฃ Mini Quiz
rx.tap
์Driver
๋ก ๋ณํํ๋ ค๋ฉด?tableView.rx.modelSelected
์ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์์ ?rx.text
๊ฐ Optional์ธ ์ด์ ๋?
๋ค์ โถ๏ธ gesture_keyboard.md ๋ก ์ด๋ํด Gesture Recognizer & Keyboard reactive ํจํด์ ๋ฐฐ์๋ด ์๋ค. ๐
Last updated