晚上,在我的应用程序中,我不想使用RxCocoa,并且尝试符合tableview数据源和委托,但是遇到了一些问题。
如果不使用RxCocoa或RxDataSource,我将找不到任何指南。
在我的ViewModel中,有一个lazy computed var myData: Observable<[MyData]>
,但我不知道如何获取行数。
我当时正在考虑将可观察对象转换为行为主题,然后获取值,但我真的不知道哪个是这样做的最佳选择。
答案 0 :(得分:1)
您需要创建一个符合UITableViewDataSource以及观察者的类。一个快速而肮脏的版本看起来像这样:
class DataSource: NSObject, UITableViewDataSource, ObserverType {
init(tableView: UITableView) {
self.tableView = tableView
super.init()
tableView.dataSource = self
}
func on(_ event: Event<[MyData]>) {
switch event {
case .next(let newData):
data = newData
tableView.reloadData()
case .error(let error):
print("there was an error: \(error)")
case .completed:
data = []
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = data[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// configure cell with item
return cell
}
let tableView: UITableView
var data: [MyData] = []
}
将此类的实例作为您的视图控制器的属性。
像这样将您的myData
绑定到它:
self.myDataSource = DataSource(tableView: self.tableView)
self.myData
.bind(to: self.myDataSource)
.disposed(by: self.bag)
(我在上面放置了所有self
,以使内容更清楚。)
您可以对此进行优化,以至于可以有效地重新实现RxCoca的数据源,但这又意味着什么呢?