Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PoohSunny/71e22845a2b2317e0457a0c1710d0895 to your computer and use it in GitHub Desktop.
Save PoohSunny/71e22845a2b2317e0457a0c1710d0895 to your computer and use it in GitHub Desktop.
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let viewModel = ViewModel()
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
viewModel.items.bind(to: tableView.rx.items) { (_: UITableView, index: Int, item: Model) in
let indexPath = IndexPath(item: index, section: 0)
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = item.name
return cell
}.addDisposableTo(disposeBag)
viewModel.defaultIndex.subscribe { event in
switch event {
case .success(let indexPath):
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: UITableViewScrollPosition.none)
case .error(let indexPath):
print("Error: ", indexPath)
}
}
.disposed(by: disposeBag)
tableView.rx.itemSelected.asDriver().drive(
onNext: { [weak self] indexPath in
guard let `self` = self, (self.tableView.cellForRow(at: indexPath) != nil) else {
return
}
self.viewModel.select(with: indexPath)
}
).addDisposableTo(disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class ViewModel {
let items = Observable.just([Model(code: 1, name: "A"), Model(code: 2, name: "B"), Model(code: 3, name: "C")])
var defaultIndex: Single<IndexPath>
init() {
defaultIndex = Single<IndexPath>.create { single in
single(.success(IndexPath(item: 1, section: 0))) // just hardcoding for now, later I want to create this value from database.
return Disposables.create {}
}
}
func select(with: IndexPath) {
// store anywhere
}
}
class Model {
let code: Int
let name: String
init(code: Int, name: String) {
self.code = code
self.name = name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment