I learned example in the demo to create a UITableView and render cells.
In my opinion, items
is viewModel, I want to request some data across network by using Alamofire or other library. When I get the response, How can I update the cell's text relevant?
In the other words, I want to bind viewModel to Cells. When the model's data changed, cell's content could changed automatically.
I have a idea is: create a Observable sequence for the cell's content (bind to cell).When the server response data, it call function tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
. But this seems not a grace or good method.
So, hope some can help me :)
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bindTo(tableView.rx_itemsWithCellIdentifier("Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = "\(element) @ row \(row)"
/* to do some binding or something else ? */
}
.addDisposableTo(disposeBag)
tableView
.rx_modelSelected(String)
.subscribeNext { value in
DefaultWireframe.presentAlert("Tapped `\(value)`")
}
.addDisposableTo(disposeBag)
Your client
(Alomofire, ...) will have some like this:
func searchSomething() -> Observable<[YourModel]>
In the viewModel
you will have the items
property:
private(set) lazy var items : Observable<[YourModel]> =
self.client.searchSomething()
.observeOn(MainScheduler.instance)
.shareReplay(1)
And then, in the viewController
:
tableView.dataSource = nil
// Bind the items to the table view data source
viewModel.items
.bindTo(tableView.rx.items) { tableView, index, item in
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell.textLabel?.text = item.title // if item.title is a String
return cell
}
.addDisposableTo(disposeBag)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With