S Kurganov
S Kurganov

Reputation: 1

RxSwift, How to draw tableView without using RxDataSourced?

I can't figure out how to do your dataSource. I watched lessons on RxSwift and RxCocoa and realized that for complex tables you need to use your datasource. Found a library RxDataSourced but we're not allowed to use it. Decided to write your own dataSource but nothing happened. If you don't mind can you show examples of writing dataSourse found nothing on the Internet.

class RXSpecificationsDataSource: NSObject, RxTableViewDataSourceType, UITableViewDataSource {
    typealias Element = MaterialEntityRootGroupProperty

    var _sectionModels: [MaterialEntityRootGroupProperty] = []


     public typealias ConfigureCell = (RXSpecificationsDataSource, UITableView, IndexPath) -> UITableViewCell



    func tableView(_ tableView: UITableView, observedEvent: Event<RXSpecificationsDataSource.Element>) { }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard _sectionModels.count > section else { return 0 }
       return _sectionModels[section].properties.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        precondition(indexPath.item < _sectionModels[indexPath.section].properties.count)  return ConfigureCell(self, tableView, indexPath, self[indexPath])

    }

    func numberOfSections(in tableView: UITableView) -> Int {
       return _sectionModels.count
    }
}

final class MaterialDetailSpecificationsView: UserInterface {

    private var specificationTableView: UITableView!
    private let disposeBag = DisposeBag()

    func setupView(items: Variable<[MaterialEntityRootGroupProperty]>) {
        setNabigationParms()
        drawTableViewSpecifications()

        let dataSource = RXSpecificationsDataSource ()

        dataSource.configureCell = { (dataSource, tv, indexPath, element) in
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
            return cell
        }

        items.asObservable()
            .bind(to: specificationTableView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)



    }

Upvotes: 0

Views: 1989

Answers (1)

Shai Mishali
Shai Mishali

Reputation: 9402

You do not need RxDataSources just to bind a stream to a table. There are already built-in bindings for UITableView and UICollectionView inside RxCocoa, you can see some more information here:

There's actually an example of how to do this without RxDataSources, inside the RxDataSources repo ;-)

let data = Observable<[String]>.just(["first element", "second element", "third element"])

data.bind(to: tableView.rx.items(cellIdentifier: "Cell")) { index, model, cell in
  cell.textLabel?.text = model
}
.disposed(by: disposeBag)

https://github.com/RxSwiftCommunity/RxDataSources#why

Upvotes: 1

Related Questions